code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Co...
684
import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] , lowerCAmelCase: str , lowerCAmelCase: str )...
300
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : Dict = { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-d...
649
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 BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResamp...
649
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = "" for i in table: res += inp[i - 1] return res def lowerCamelCase__ (__lowerCamelCase ): return data[1:] + data[0] def ...
249
import torch from torch import nn class __magic_name__ ( nn.Module ): def __init__( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Any=1 , Upp...
323
0
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_sha...
721
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( 'The `inpainting.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionInpaintPipeline` instead.' )
230
0
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset _lowercase : Union[str, Any] = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1),...
641
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Any = logging.get_logger(__name__) _lowercase : Union[str, Any] = { "snap-research/efficientformer-l1-300": ( "https://huggingface.co/snap-research...
641
1
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = int(_UpperCamelCase ) # Initialize Result __lowerCAmelCase = [] # Traverse through all denomination for denomination in rever...
282
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = len(_UpperCamelCase ) print("The following activities are selected:" ) # The first activity is always selected __lowerCAmelCase = ...
282
1
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transfor...
667
'''simple docstring''' from __future__ import annotations def a ( lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' if partitions <= 0: raise ValueError("""partitions must be a positive number!""" ) if partitions > number_of_bytes: raise ValueE...
667
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...
313
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 torch ...
313
1
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner ...
61
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A__ : List[str] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['Bi...
353
0
"""simple docstring""" from math import sqrt def _lowerCAmelCase ( UpperCamelCase_ ): 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 3 are not primes return...
248
"""simple docstring""" from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class SCREAMING_SNAKE_CASE_ : """simple docstring""" __lowercase : int __lowercase : TreeNode | None = None __lowercase ...
248
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { """microsoft/unispeech-sat-base-100h-libri-ft""": ( """h...
0
"""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_roformer import RoF...
163
0
'''simple docstring''' import numpy as np def lowercase__ ( __UpperCamelCase : np.array ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowercase__ ( __UpperCamelCase : np.array ): '''simple docstring''' return vector * sigmo...
339
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase : int | str ): '''simple docstring''' __lowercase = str(__UpperCamelCase ) return n == n[::-1] def lowercase__ ( __UpperCamelCase : int = 1000000 ...
339
1
from importlib import import_module from .logging import get_logger snake_case__ : Any = get_logger(__name__) class _A : '''simple docstring''' def __init__( self : Optional[int] , lowerCamelCase : Optional[Any] , lowerCamelCase : List[Any]...
402
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor snake_case__ : Optional[Any] = logging.get_logger(__name__) class _A ( _lowercase ): '''simple docstring''' def __init__( self : Dict , *lowerCam...
402
1
from __future__ import annotations from collections.abc import Iterator class UpperCamelCase : """simple docstring""" def __init__( self : Optional[int] ,_SCREAMING_SNAKE_CASE : Any ) -> Tuple: '''simple docstring''' A = value A = None ...
702
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def snake_case ( UpperCAmelCase : List[str] ): # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unifi...
110
0
"""simple docstring""" def _UpperCamelCase ( _A , _A ) -> bool: """simple docstring""" _UpperCAmelCase = len(_A ) _UpperCAmelCase = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by no...
555
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging a : Dict = logging.get_logger(__name__) # TODO: upload to AWS a : Tuple = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/ret...
555
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_nump...
242
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { ...
242
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 from ...test_model...
288
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_mode...
288
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transforme...
719
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, id...
380
0
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _A : Optional[int] = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ ...
427
'''simple docstring''' import math def UpperCamelCase_ ( snake_case_ : float , snake_case_ : float ) -> float: '''simple docstring''' if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values o...
427
1
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCAmelCase__ ( lowerCamelCase ): lowercase :List[str] = FileLock(str(tmpdir / "foo.lock" ) ) lowercase :Tuple = FileLock(str(tmpdir / "foo.lock" ) ) lowercas...
719
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _UpperCAmelCa...
453
0
'''simple docstring''' from maths.prime_check import is_prime def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] ): '''simple docstring''' if not isinstance(__lowerCamelCase , __lowerCamelCase ): _UpperCAmelCase : int =f"Input value of [num...
446
import cva import numpy as np class snake_case : '''simple docstring''' def __init__( self : Any , lowerCAmelCase_ : float , lowerCAmelCase_ : int ) -> List[Any]: """simple docstring""" if k in (0.04, 0.06): SCREAMING_SN...
393
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_ut...
346
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase :List[str] = logging.get_logger(__name__) lowerCamelCase :List[str] = {} class UpperCAmelCase ( __snake_case ): a: str = "llama" a: List[str] ...
346
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpo...
24
def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' while a != 0: UpperCAmelCase_, UpperCAmelCase_ : Optional[int] = b % a, a return b def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' ...
30
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatt...
410
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ : int = logging.get_logger(__name__) __magic_name__ : Optional[Any] = { '''uclanlp/visualbert-vqa''': '''https://huggingface.co/uclanlp/visualbert-v...
410
1
import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoa...
439
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 impor...
439
1
'''simple docstring''' from __future__ import annotations import math def __lowerCAmelCase ( lowerCamelCase : List[str] , lowerCamelCase : Dict ): '''simple docstring''' __lowerCAmelCase = u for i in range(1 , lowerCamelCase ): __lowerCAmel...
720
'''simple docstring''' def __lowerCAmelCase ( lowerCamelCase : Union[str, Any] ): '''simple docstring''' __lowerCAmelCase = 1 __lowerCAmelCase = 2 while i * i <= n: __lowerCAmelCase = 0 while n % i == 0: n //= i multiplicity += 1 ...
39
0
'''simple docstring''' import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger _A = get_logger(__name__) _A = R"""\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)...
158
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { 'RWKV/rwkv-4-169m-pile': 'https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json', '...
389
0
"""simple docstring""" def __a ( _SCREAMING_SNAKE_CASE = 1000 ) ->int: a__: List[Any] = 3 a__: Any = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"{s...
217
"""simple docstring""" import logging import os import threading import time try: import warnings except ImportError: lowercase__ = None try: import msvcrt except ImportError: lowercase__ = None try: import fcntl except ImportError: lowercase__ = None # Backward compatibility # -----...
217
1
'''simple docstring''' def A_( A : str): UpperCamelCase = [0] * len(A) for i in range(1 , len(A)): # use last results for better performance - dynamic programming UpperCamelCase = prefix_result[i - 1] while j > 0 and in...
3
'''simple docstring''' import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def ...
683
0
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merge...
510
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def _UpperCAmelCase ( A ): '''simple docstring''' return ConvertCommand( args.model_type , args.tf_checkpoint , ...
510
1
# 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 requ...
39
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB 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/license...
182
0
import unittest import numpy as np import requests 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_...
298
from ...configuration_utils import PretrainedConfig from ...utils import logging __a : int = logging.get_logger(__name__) __a : Tuple = { '''uclanlp/visualbert-vqa''': '''https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json''', '''uclanlp/visualbert...
298
1
"""simple docstring""" def _snake_case ( snake_case__ : int ): if divisor % 5 == 0 or divisor % 2 == 0: return 0 A = 1 A = 1 while repunit: A = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def _snake_case ( snake_case__ : int = 100_0000 ): A ...
91
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCAmelCase : str = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask...
584
0
from __future__ import annotations def A ( __UpperCAmelCase ) -> list[int]: '''simple docstring''' return [ord(__UpperCAmelCase ) - 96 for elem in plain] def A ( __UpperCAmelCase ) -> str: '''simple docstring''' return "".join(chr(ele...
561
import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging UpperCamelCase_ = logging.get_logger(__name__) def A ( ) -...
561
1
'''simple docstring''' from collections.abc import Callable class _snake_case : def __init__( self ,_snake_case = None ): # Stores actual heap items. UpperCAmelCase_ : list = [] # Stores indexes of each item for supporting updates and deletion. Upper...
71
'''simple docstring''' import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class __UpperCamelCase...
476
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class _a ( __lowerCame...
706
"""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_availabl...
95
0
def lowerCamelCase__ ( _a , _a): return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): assert xnor_gate(0 , 0) == 1 assert xnor_gate(0 , 1) == 0 assert xnor_gate(1 , 0) == 0 assert xnor_gate(1 , 1) == 1 if __name__ == "__main__": print...
25
"""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_a...
450
0
"""simple docstring""" def _UpperCAmelCase ( lowerCamelCase__ ): # noqa: E741 """simple docstring""" lowerCAmelCase__ = len(lowerCamelCase__ ) lowerCAmelCase__ = 0 lowerCAmelCase__ = [0] * n lowerCAmelCase__ = [False] * n lowerCAmelCase...
704
"""simple docstring""" from __future__ import annotations from math import gcd def _UpperCAmelCase ( lowerCamelCase__ , lowerCamelCase__ = 2 , lowerCamelCase__ = 1 , lowerCamelCase__ = 3 , ): """simple docstring""" if num < 2: raise ValueError("""The input value ca...
674
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, l...
244
'''simple docstring''' 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...
244
1
from collections.abc import Sequence def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: Sequence[float] , __lowerCamelCase: bool = False ): '''simple docstring''' if not arr: return 0 lowercase_ = 0 if allow_empty_subarrays else float("-inf" ) lowercase_ = 0.0 for n...
601
import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, Trai...
601
1
'''simple docstring''' # Algorithm for the pigeonhole sorting def __lowerCamelCase ( __lowerCAmelCase : Dict ) -> int: snake_case = min(lowerCamelCase_ ) # min() finds the minimum value snake_case = max(lowerCamelCase_ ) ...
369
def lowerCAmelCase__ ( lowerCamelCase_ : Dict ,lowerCamelCase_ : Optional[int]): '''simple docstring''' lowerCAmelCase__ : int = (boundary[1] - boundary[0]) / steps lowerCAmelCase__ : Optional[int] = boundary[0] lowerCAmelCase__ : ...
647
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCAmelCase__ : Union[str, Any] = False class ...
632
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_co...
632
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 ( ...
97
from manim import * class A__ ( __snake_case ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = Rectangle(height=0.5 ...
280
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { """EleutherAI/gpt-neox-20b""": """https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json"...
717
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementati...
14
0
'''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/LICENSE...
638
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, ...
638
1
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time lowerCAmelCase_ = Lock() def __lowerCAmelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCa...
710
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { """configuration_lilt""": ["""LILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LiltConfig"""], } try: if not is_torch_available(): raise OptionalDependen...
470
0
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, require_torch @require_torch @r...
124
import os import sys import unittest snake_case : List[Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_...
124
1
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer __magic_name__ = logging.get_logger(__name__) __magic_name...
679
from __future__ import annotations __magic_name__ = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def UpperCAmelCase__( __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[int] ...
679
1
"""simple docstring""" import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def s...
95
"""simple docstring""" from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = '''T5Config''' class Upper...
95
1
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRL...
452
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { '''microsoft/unispeech-large-1500h-cv''': ( '''https://huggingface.co/microsoft/unispeech-large-1500h...
452
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase : List[str] = { '''configuration_distilbert''': [ '''...
454
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { "microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json", # See all BioGPT models at https://huggin...
699
0
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class UpperCamelCase : def __init__(self : str...
708
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class UpperCamelCase : def __init__(self : Tup...
192
0
'''simple docstring''' from collections.abc import Callable import numpy as np def _snake_case ( A , A , A , A , A ) -> np.array: lowerCAmelCase__ = int(np.ceil((x_end - xa) / step_size ) ) lowerCAmelCase__ ...
90
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase__ : list[int] , UpperCamelCase__ : str ): """simple docstring""" a_ : Tuple = int(UpperCamelCase__ ) # Initialize Result a_ : Tuple ...
442
0
def _lowerCamelCase ( lowerCamelCase_ : int ): """simple docstring""" if number > 0: raise ValueError('input must be a negative integer' ) UpperCAmelCase_ : Optional[int] = len(bin(lowerCamelCase_ )[3:] ) UpperCAmelCase_ ...
706
'''simple docstring''' import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRo...
389
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, ...
62
'''simple docstring''' import math def __UpperCAmelCase ( a_: int ): _UpperCAmelCase : Any = [True] * n _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : str = False _UpperCAmelCase : int = True for i in range(3, int(n**...
494
0
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast a_ : str = datasets.utils.logging.get_logger(__name__) @dataclass class _snake_case ( datasets...
444
from abc import ABC, abstractmethod from typing import List, Optional class _snake_case ( A__ ): def __init__( self) -> int: # test for the above condition self.test() def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE...
444
1
'''simple docstring''' import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils...
347
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a : """simple docstring""" def __init__( self : Optional[Any] , snake_case_ : List[str]=2 ...
347
1
"""simple docstring""" __SCREAMING_SNAKE_CASE ={ "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", ...
477
"""simple docstring""" import numpy as np def lowercase__( __SCREAMING_SNAKE_CASE : np.array ): return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
477
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'...
61
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_sentencepiec...
488
0
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_...
260
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging...
260
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '''▁''' _A = {'''vocab_file'''...
431
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer _A = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}...
258
0
'''simple docstring''' def snake_case_ (_a : float , _a : float ): if mass < 0: raise ValueError('''The mass of a body cannot be negative''' ) return 0.5 * mass * abs(_a ) * abs(_a ) if __name__ == "__main__": import doctest doctest.testmod(verbos...
358
'''simple docstring''' def snake_case_ (_a : list[list[int]] , _a : int , _a : int , _a : list[int] ): # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False ...
358
1
__UpperCamelCase : int = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ __UpperCamelCase : ...
80
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration lowerCAmelCase_ : List[Any] = [ # tf -> hf ('/', '.'), ('layer_',...
692
0
import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_...
700
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCamelCase__ = { """configuration_ctrl""": ["""CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CTRLConfig"""], """tokenization_ctrl""": ["""CTRLTokenizer"""], }...
552
0
def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ) -> int: '''simple docstring''' def update_area_of_max_square(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CA...
663
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_...
663
1
'''simple docstring''' 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 Opt...
712
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: Any = logging.get_logger(__name__) A__: List[str] = { ...
506
0
"""simple docstring""" import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_...
102
"""simple docstring""" def snake_case ( _a: int , _a: int )-> int: '''simple docstring''' lowerCamelCase__ = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): lowerCamelCase__ = n - k # Calc...
510
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.uti...
704
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import...
415
0
"""simple docstring""" def lowerCamelCase_ ( __lowerCAmelCase , __lowerCAmelCase ) -> Dict: '''simple docstring''' lowerCamelCase__ =0 lowerCamelCase__ =len(__lowerCAmelCase ) - 1 while left <= right: # avoid divided by 0 during interp...
530
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class __UpperCAmelCase ( __lowerCAmelCase ): A__...
530
1
class __SCREAMING_SNAKE_CASE: def __init__( self: List[str] ) -> Optional[int]: snake_case__ = 0 snake_case__ = 0 snake_case__ = {} def lowerCAmelCase_ ( self: Any , UpperCamelCase: ...
704
from argparse import ArgumentParser from .env import EnvironmentCommand def a_ ( ) -> Optional[Any]: """simple docstring""" snake_case__ = ArgumentParser('Diffusers CLI tool' , usage='diffusers-cli <command> [<args>]' ) snake_case__ ...
372
0
'''simple docstring''' import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class UpperCAmelCase_ (tf.keras.optimizers.schedules.Learni...
13
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 : Tuple = "." # Internal T...
468
0
'''simple docstring''' import re from ..utils import cached_file # docstyle-ignore lowerCamelCase :int = ''' Human: <<task>> Assistant: ''' lowerCamelCase :Union[str, Any] = '''huggingface-tools/default-prompts''' lowerCamelCase :List[Any] = {'...
712
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase :Any = logging.get_logger(__name__) lowerC...
686
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase =logging.get_logger(__name__) UpperCamelCase ={ "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder...
208
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate UpperCamelCase =TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow("", "|",...
208
1
'''simple docstring''' from torch import nn class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : Optional[int] , __a : Tuple ): super().__init__() _a =...
521
'''simple docstring''' import os from datetime import datetime as dt from github import Github lowerCAmelCase_ : List[Any] = [ 'good first issue', 'feature request', 'wip', ] def _lowerCamelCase ( ) -> Dict: _a = Github(os.environ["GITH...
521
1
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 1 / sqrt(2 ) ): __snake_case : List[Any] = tau * frequency / samplerate __snake...
81
_snake_case : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _snake_case : Dict = ["a", "b", "c", "d", "e"] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case ...
81
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils impor...
721
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, ...
205
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTeste...
26
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __magic_name__ : Optional[int] = { """configuration_biogpt""": ["""BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BioGptConfig"""], """token...
615
0
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _A = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model"...
717
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 = logging.get_logger(__name__) _A = { "sail/poolformer_s12":...
294
0
"""simple docstring""" def _lowercase ( __snake_case ,__snake_case ) -> int: return int((input_a, input_a).count(1 ) != 0 ) def _lowercase ( ) -> None: assert or_gate(0 ,0 ) == 0 assert or_gate(0 ,1 ) == 1 assert or...
293
"""simple docstring""" import argparse from collections import defaultdict def _lowercase ( __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> Optional[int]: __lowerCAmelCase : str = F"""{file}_{class_name}_{test_name}""" don...
293
1
"""simple docstring""" def lowerCAmelCase_( lowercase_ : list[int] ) -> float: if not nums: # Makes sure that the list is not empty raise ValueError('''List is empty''' ) _lowerCamelCase = sum(lowercase_ ) / len(lowercase_ ) # Calculate t...
708
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __SCREAMING_SNAKE_CASE : List[Any] = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMO...
623
0
'''simple docstring''' 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_fast import BertTokenizerFast from .tokenizatio...
28
"""simple docstring""" # Lint as: python3 import itertools import os import re _snake_case = re.compile(r'([A-Z]+)([A-Z][a-z])') _snake_case = re.compile(r'([a-z\d])([A-Z])') _snake_case = re.compile(r'(?<!_)_(?!_)') _snake_case = re.compile(r'(_{2,})'...
389
0
"""simple docstring""" import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _snake_case = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS...
659
"""simple docstring""" def snake_case ( _a: int , _a: list[int] , _a: int )-> int: '''simple docstring''' def count_of_possible_combinations(_a: int ) -> int: if target < 0: return 0 if target == 0: ...
659
1
"""simple docstring""" def _snake_case ( snake_case__ : str , snake_case__ : str = " " ): A = [] A = 0 for index, char in enumerate(snake_case__ ): if char == separator: split_words.append(string[last_index:index] ) A = index + 1 elif index + 1 == len(snake_case__ ): ...
91
def SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , snake_case ) -> int: # Return True if there is node that has not iterated. __lowercase = [False] * len(snake_case ) __lowercase = [] queue.append(snake_case ) ...
375
0
import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class lowerCamelCase__( nn.Module): UpperCAmelCase__ : int UpperCAmelCase__ : int UpperCAmelCase...
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class lowerCamelCase__( unittest.TestCase...
80
0
"""simple docstring""" 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 mus...
409
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_C...
111
0
import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 __SCREAMING_SNAKE_CASE : str = 0b10_11_00_11_11_10_11_00_10_01_00_00_01_11_10...
705
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel __SCREAMING_SNAKE_CASE : List[str] = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''at...
149
0
"""simple docstring""" 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 fr...
567
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_attention_mask ...
297
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import f...
706
'''simple docstring''' _lowerCAmelCase : List[str] = {str(digit): digit**5 for digit in range(10)} def __UpperCamelCase ( _A : int ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(_A ) ) def __UpperCamelCase ( ) ...
646
0
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_availa...
202
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, ...
202
1
def _lowercase ( SCREAMING_SNAKE_CASE_ : int = 200 ): """simple docstring""" UpperCamelCase = [1, 2, 5, 10, 20, 50, 100, 200] UpperCamelCase = [0] * (pence + 1) UpperCamelCase = 1 # base case: 1 way to make 0 pence for coin...
181
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _lowercase ( *SCREAMING_SNAKE_CASE_ : List[Any] ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE...
181
1
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableU...
622
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__( lowerCamelCase , unittest.TestCase ): '''simple docstring''' A : int ...
622
1
def _snake_case (__lowercase , __lowercase): _enforce_args(__lowercase , __lowercase) if n == 0: return 0 UpperCamelCase_ = float('-inf') for i in range(1 , n + 1): UpperCamelCase_ = max( __lowercase , ...
618
def _snake_case (__lowercase , __lowercase): _enforce_args(__lowercase , __lowercase) if n == 0: return 0 UpperCamelCase_ = float('-inf') for i in range(1 , n + 1): UpperCamelCase_ = max( __lowercase , ...
618
1
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimen...
48
def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase) -> float: if density <= 0: raise ValueError("Impossible fluid density") if bulk_modulus <= 0: raise ValueError("Impossible bulk modulus") return (bulk_modulus / density) ** 0.5 if __name__ == "_...
515
0
"""simple docstring""" import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( """The `inpainting.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionInpaintPipeli...
715
"""simple docstring""" import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCas...
176
0
"""simple docstring""" from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass _snake_case = (3, 9, -11, 0, 7, 5, 1, -1) _snake_case = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class _a : a_ : int ...
510
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torc...
264
0
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig _lowerCAmelCase = { '''susnato/ernie-m-base_pytorch''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json''', '''susnato/ernie-m-lar...
160
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor _lowerCAmelCase = logging.get_logger(__name__) class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' def __init__( s...
160
1
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class _snake_case ( unittest.TestCase ): def _lowerCamelCase ( self: List[str] ) -> List[str]: __UpperCAmelCase : Any = get_activati...
382
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ = { "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"], "processing_vision_text_dual_encoder...
393
0
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from tra...
715
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate...
507
0
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 accelerate import Accelerator, Dist...
84
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxT...
84
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase : Tuple = { "configuration_blip_2": [ "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Blip2Config", "Blip2QFormerConfig", "Bli...
284
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging ...
284
1