code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common impo...
47
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 transformers...
90
0
from __future__ import annotations from typing import Generic, TypeVar UpperCamelCase__ : Dict = TypeVar("""T""") class lowerCamelCase_ ( Generic[T] ): def __init__( self : Dict ,__lowerCamelCase : T ): '''sim...
330
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''AT...
330
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """microsoft/unispeech-sat-base-100h-libri-ft""": ( """https://huggingface.co/microsoft...
256
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCAmelCase = logging.get_logger(__na...
256
1
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeli...
368
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A ( UpperCAmelCase__ ): '''s...
146
0
"""simple docstring""" import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __snake_case ( ...
290
"""simple docstring""" def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: if height >= 1: move_tower(height - 1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) move_dis...
290
1
'''simple docstring''' def __lowercase ( __lowercase ) -> list: '''simple docstring''' _A = len(__lowercase ) for _ in range(__lowercase ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: ...
367
'''simple docstring''' import operator def __lowercase ( __lowercase , __lowercase = False , __lowercase = None ) -> list: '''simple docstring''' _A = operator.lt if reverse else operator.gt _A = solution or [] if not arr:...
174
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBa...
48
def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Any: # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) lowerCamelCase : str = (boundary[1] - boundary[0]) / steps lowerCamelCase : List[str] = boundary[0]...
48
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _SCREAMING_SNAKE_CASE = {'''configuration_wavlm''': ['''WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WavLMConfig''']} try: if not is_torch_available(): raise ...
365
'''simple docstring''' import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformer...
217
0
'''simple docstring''' from __future__ import annotations a_ : Optional[int] = list[list[int]] # assigning initial values to the grid a_ : List[str] = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0...
75
import os import pytest from transformers.dynamic_module_utils import get_imports snake_case_ = '\nimport os\n' snake_case_ = '\ndef foo():\n import os\n return False\n' snake_case_ = '\ndef foo():\n def bar():\n if True:\n import os\n return...
24
0
'''simple docstring''' import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel,...
364
'''simple docstring''' from collections import defaultdict def _UpperCAmelCase ( _UpperCamelCase : int ) -> int: A_ = 1 A_ = True for v in tree[start]: if v not in visited: ret += dfs(_UpperCamelCase ) if ret ...
18
0
'''simple docstring''' from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import to...
272
'''simple docstring''' from math import sqrt def snake_case__ ( _A: int = 1000000 ) -> int: '''simple docstring''' lowerCAmelCase = 0 lowerCAmelCase = 0 lowerCAmelCase = 42 while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides ...
272
1
from sklearn.metrics import matthews_corrcoef import datasets lowercase_ = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false p...
194
import warnings from .generation import TFGenerationMixin class A_ ( __UpperCamelCase ): '''simple docstring''' warnings.warn( """Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will """ """be removed in Transformers v5. Impor...
194
1
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _UpperCAmelCase ( a__ ): """simple docstring""" ...
284
'''simple docstring''' from math import log from scipy.constants import Boltzmann, physical_constants __A =3_00 # TEMPERATURE (unit = K) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ): if donor_conc <= ...
163
0
"""simple docstring""" from __future__ import annotations import numpy as np def lowerCamelCase ( _UpperCamelCase : list[float] ) -> Optional[Any]: '''simple docstring''' return np.maximum(0 , _UpperCamelCase ) if __name__ == "__main__": print(np.array...
354
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : List[str] = { 'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'], ...
320
0
from __future__ import annotations from typing import Generic, TypeVar a_ = TypeVar("""T""") class __lowerCAmelCase ( Generic[T] ): def __init__( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = data __lowerCamelCase = self ...
330
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: ...
330
1
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torc...
353
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''', # See all PEGASUS models ...
288
0
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor A__ : Optional[Any] = logging.get_logger(__name__) class __snake_case ( UpperCamelCase_ ): def __init__( self : Any , *A_ : L...
103
def _a ( SCREAMING_SNAKE_CASE : int = 1000000 ): """simple docstring""" UpperCamelCase__ : Any = set(range(3 , SCREAMING_SNAKE_CASE , 2 ) ) primes.add(2 ) for p in range(3 , SCREAMING_SNAKE_CASE , 2 ): if p not in primes: continue ...
146
0
'''simple docstring''' from collections import namedtuple SCREAMING_SNAKE_CASE_: Tuple =namedtuple('from_to', 'from_ to') SCREAMING_SNAKE_CASE_: Union[str, Any] ={ 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 10_00), 'kilolitre': from_to(1, 1), 'gallon': from_to(0....
351
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE_: int ={ 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'configuratio...
106
0
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments a : Optional[Any] = logging.getLogger(__name__) @dataclass class _a ( __A ): ...
147
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _UpperCAmelCase : Any = { """configuration_trocr""": ["""TROCR...
174
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=__lowerCamelCase ) class __A( __lowerCamelCase ): """simple docstring""" # `task` is not a ClassVar since we want it to be part of the...
178
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available()...
178
1
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( unittest.Tes...
24
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A = logging.get_logger(__name__) __A = { "SenseTime/deformable-detr": "https://huggingface.co/sensetime/deformable-detr/r...
217
0
def lowerCamelCase__ ( snake_case_ : Tuple , snake_case_ : Union[str, Any] ) -> Optional[int]: __snake_case = 0 __snake_case = len(__lowerCAmelCase ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_co...
371
import math def lowerCamelCase__ ( snake_case_ : int ) -> list[int]: __snake_case = [] __snake_case = 2 __snake_case = int(math.sqrt(snake_case_ ) ) # Size of every segment __snake_case = [True] * (end + 1) ...
238
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.ut...
80
def _snake_case ( lowerCAmelCase : list ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = len(lowerCAmelCase ) for i in range(1 , lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : int = collection[i] SCREAMING_SNAKE_CASE_ : Any = 0 SCRE...
18
0
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging __snake_case =logging.get_logger(__name__) __snake_case ={ """Visual-Attention-Network/van-base""": ( """https://huggingface.co/Visual-Attention-Network/van-bas...
55
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __snake_case =TypeVar("""T""") class UpperCAmelCase_ ( Generic[T] ): def __init__( self : int , UpperCAmelCase__ : T )...
55
1
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> int: """simple docstring""" if not numbers: return 0 if not isinstance(__snake_case, (list, tuple) ) or not all( isinstance(__snake_case, __snake_case ) for number ...
194
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> bool: """simple docstring""" return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def lowerCamelCase__ ( __snake_case ) -> bool: ...
194
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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_...
124
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case...
124
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from d...
344
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCamelCase ( metaclass=a__ ): '''simple docstring''' A_ : Optional[Any] = ['flax'] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: ...
320
0
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 a ( UpperCAmelCase ): def __in...
189
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoo...
189
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class A__ ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = ['torch', 'transformers', 'onnx'] def __init__( self: Dict , *_S...
269
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self: Optional[int] ...
269
1
'''simple docstring''' from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class a__ ( lowerCamelCase_ ): _SCREAMING_SNAKE_CASE : Tuple = """philschmid/bart-large-cnn-samsum""" _SCREAMING_SNAKE_CASE : str = ( """...
357
'''simple docstring''' import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data i...
199
0
'''simple docstring''' from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline UpperCamelCase_ = logging.get_logger(__name__) class a_ ...
309
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __UpperCamelCase : Tuple = TypeVar('''T''') class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" lowerc...
106
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class __lowercase ( Tensor...
127
import torch from diffusers import StableDiffusionPipeline lowerCAmelCase : Any = """path-to-your-trained-model""" lowerCAmelCase : int = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("""cuda""") lowerCAmelCase : Union[str, Any...
127
1
from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...t...
178
import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transform...
178
1
import math def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> Dict: """simple docstring""" return math.sqrt(__a ) * math.sqrt(__a ) == num def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> Union[str, Any]: """simple docstring""" UpperCame...
350
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, load_image, lo...
60
0
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: if b == 0: return (1, 0) (UpperCamelCase__) : Any = extended_euclid(__lowerCamelCase , a % b ) UpperCam...
189
"""simple docstring""" import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_P...
238
0
"""simple docstring""" from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def _snake_case ( ): A__ = [randint(-1000 , 1000 ) for i in range(10 )] A__ = ...
358
"""simple docstring""" import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl....
69
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a_ : List[str] = {"""configuration_plbart""": ["""PLBART_PRETRAINED_C...
55
'''simple docstring''' from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, float...
55
1
def UpperCAmelCase__ (UpperCamelCase_ ,UpperCamelCase_ ): """simple docstring""" if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) snake_case = str(bin(UpperCamelCase_ ) )[2:] # remove the lea...
213
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _SCREAMING_SNAKE_CASE : str = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def UpperCAmelCase__ (UpperCamelCase_ = "mumbai" ): ...
213
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : Optional[int] = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'],...
124
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...
124
1
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a_ : int = logging.get_logger(__name__) a_ : Tuple ...
6
'''simple docstring''' from argparse import ArgumentParser from . import BaseTransformersCLICommand def a_ ( __snake_case : Tuple ) -> str: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force ,...
6
1
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Optional[Any]: if not head: return True # split the list to two parts UpperCamelCase__ , UpperCamelCase__ : List[str] = head.next, head while fast and fast.next: UpperCamelCas...
189
# 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 # # U...
189
1
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza,...
308
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFa...
308
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "tokenizer"] __Up...
91
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor,...
199
0
import numpy as np class _a : def __init__( self : Tuple, lowerCAmelCase__ : Optional[Any]=None, lowerCAmelCase__ : Optional[Any]=None, lowerCAmelCase__ : List[Any]=None, lowerCAmelCase__ : Optional[Any]=None, lowerCAmelCase__ : List[Any]=None ...
370
"""simple docstring""" from __future__ import annotations import math def a_ ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) ...
128
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 _SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) _SCREAMI...
127
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_torch_tpu_available(check_de...
127
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { 'microsoft/markuplm-base': 'https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json', 'microsoft/markuplm-large': 'https://huggingf...
355
class __snake_case : def __init__( self , snake_case__ ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : Tuple =n UpperCAmelCase : Any =[None] * self.n UpperCAmelCase : Tuple =0 # index of the first e...
78
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, ...
20
"""simple docstring""" import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from fla...
60
0
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 ...
366
from __future__ import annotations __lowerCamelCase = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } ...
10
0
import argparse from collections import defaultdict def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : List[str] = F"{file}_{class_name}_{test_name}" done...
73
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCamelCase = { '''configuration_resnet''': ['''RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Re...
69
0
import qiskit def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> qiskit.result.counts.Counts: """simple docstring""" _snake_case = qiskit.Aer.get_backend('''aer_simulator''' ) _snake_case = qiskit.QuantumCircuit(4 , 2 ) # encode inputs in qu...
278
from math import factorial def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" if n < k or k < 0: raise ValueError('''Please enter positive integers for n and k where n >= k''' ) return factorial(_UpperCamelCase ) // (factorial(_UpperCam...
278
1
"""simple docstring""" import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowercase__( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple=1 ): if n_shave_prefix_segments >= 0: r...
213
"""simple docstring""" import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassif...
213
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def A (__lowerCamelCase :int ): _lowerCAmelCase = [ """encoder.version""", """decoder.version""", """model.encoder.ve...
365
'''simple docstring''' # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position _lowercase = """2.13.1""" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("""3.7""...
229
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : Optional[int] = logging.get_logger(__name__) A : int = {'vocab_file': 'vocab.json', 'm...
6
def __lowerCAmelCase ( a__ , a__ , a__ ) -> list: __a = len(a__ ) __a = [[0] * n for i in range(a__ )] for i in range(a__ ): __a = y_points[i] for i in range(2 , a__ ): for j in range(a__ , a__ ): ...
6
1
from typing import Any class __UpperCAmelCase : '''simple docstring''' def __init__(self : Any , _lowerCAmelCase : Any ): A = data A = None def __repr__(self : List[Any] ): return F"""Node({self.data})""" class __UpperCAmelCas...
355
'''simple docstring''' 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...
337
0
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import requir...
308
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimen...
308
1
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __snake_case ( lowerCamelCase__ ): @require_torch def UpperCAmelCase__ ( self ) -> List[str]: ...
361
import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.t...
78
0
from __future__ import annotations import math def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ ) -> List[Any]: """simple docstring""" if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(_lowerCAmelCase ) == 0: raise ValueError(...
15
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar UpperCAmelCase : Dict =TypeVar("""T""") class _lowercase (Generic[T] ): '''simple docstring''' def __init__( self , snake_case__ ): ...
128
0
"""simple docstring""" def SCREAMING_SNAKE_CASE_ ( snake_case : str , snake_case : bool = False )-> str: if not isinstance(snake_case , snake_case ): _lowerCamelCase = f'Expected string as input, found {type(snake_case )}' ...
362
"""simple docstring""" import numpy as np def SCREAMING_SNAKE_CASE_ ( snake_case : np.ndarray )-> np.ndarray: return 1 / (1 + np.exp(-vector )) def SCREAMING_SNAKE_CASE_ ( snake_case : np.ndarray )-> np.ndarray: return vector * sigmoid(snake_case ) if __na...
80
0
'''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_roberta import...
47
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available snake_case_ = { """configuration_longt5""": ["""LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongT5Config""", """LongT5On...
78
0
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffuser...
361
'''simple docstring''' def a ( lowerCamelCase__ ): '''simple docstring''' return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
135
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _a = { 'configuration_convnext': ['CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvNextConf...
61
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 YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A ...
10
0
"""simple docstring""" def _a ( ) -> list[list[int]]: return [list(range(1_000 - i , -1_000 - i , -1 ) ) for i in range(1_000 )] __SCREAMING_SNAKE_CASE : Optional[Any] = generate_large_matrix() __SCREAMING_SNAKE_CASE : Optional[Any] = ( [[4,...
233
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator class __A : '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : int ) ->None: """simple docstring""" snake...
233
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 _A = logging.get_logger(__name__) _A = { '''google/mobilenet_v1_1.0_224''': '''https://hu...
278
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def __UpperCamelCase ( _A ): lowerCAmelCase_ = 384 ...
278
1
'''simple docstring''' import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallb...
106
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_: Any =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: ...
106
1
"""simple docstring""" import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import...
292
"""simple docstring""" class _UpperCAmelCase : def __init__( self :List[str] , __UpperCamelCase :Union[str, Any] , __UpperCamelCase :Tuple ): A = name A = val def __str__( self :str ): return f"{self.__class__.__nam...
292
1
from __future__ import annotations def UpperCAmelCase__ (UpperCamelCase_ ): """simple docstring""" if not nums: raise ValueError('''List is empty''' ) return sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) if __name__ == "__main__": impor...
213
import argparse import copy def UpperCAmelCase__ (UpperCamelCase_ ): """simple docstring""" snake_case = {} with open(UpperCamelCase_ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: ...
213
1
def _lowercase ( lowercase__ ): return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(UpperCAmelCase__ ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__("doctest").testmod()
275
'''simple docstring''' import math import unittest def lowerCamelCase ( UpperCAmelCase__ : int ) -> bool: assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < ...
239
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCamelCase ( metaclass=a_ ): """simple docstring""" A : Dict = ["onnx"] def __init__( self : List[str] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_...
354
'''simple docstring''' import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, ...
345
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase : int = logging.get_logger(__name__) _lowerCamelCase : List[str] = { """facebook/dat...
14
"""simple docstring""" class A_ : """simple docstring""" def __init__( self :List[str] , lowercase_ :int , lowercase_ :Optional[int]=None , lowercase_ :List[str]=None ) -> str: UpperCAmelCase = data UpperCAm...
78
0
'''simple docstring''' import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from...
160
'''simple docstring''' import os import sys import unittest lowercase : List[str] = 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, cr...
160
1
A_ :Union[str, Any] = { 'meter': 'm', 'kilometer': 'km', 'megametre': 'Mm', 'gigametre': 'Gm', 'terametre': 'Tm', 'petametre': 'Pm', 'exametre': 'Em', 'zettametre': 'Zm', 'yottametre': 'Ym', } # Exponent of the factor(meter) A_ :Option...
71
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import Toke...
80
0
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() _lowercase: List[Any] = [ "word_embeddings_layernorm.weight...
364
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration _lowercase: List[Any] = { "tiny.en": "https://openaipublic.azureedge.net/main/whisper/models/d3dd...
71
0
"""simple docstring""" import logging import os from .state import PartialState class lowerCAmelCase_ ( logging.LoggerAdapter ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Optional[int] ) -> str: A = Part...
74
"""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 import...
135
0
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTes...
143
# 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...
143
1
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffus...
233
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 Generatio...
233
1
'''simple docstring''' def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False )-> Optional[Any]: '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : ...
367
'''simple docstring''' import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import g...
349
0
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logg...
106
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __UpperCamelCase : int ...
106
1
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def a__ ( ): UpperCAmelCase_ = ArgumentParser( description=( "PyTorch TPU...
350
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { ...
241
0
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin fr...
213
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from ...
213
1
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_combinations(target - item ...
194
import warnings from .generation import TFGenerationMixin class A_ ( __UpperCamelCase ): '''simple docstring''' warnings.warn( """Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will """ """be removed in Transformers v5. Impor...
194
1
"""simple docstring""" import numpy as np def __a ( __lowerCamelCase ): return 1 / (1 + np.exp(-vector )) def __a ( __lowerCamelCase ): return vector * sigmoid(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
61
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common impor...
279
0
'''simple docstring''' from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split a_ : Tuple = datasets.load_iris() a_ : List[str] = np.array(data["""data"""]) a_ : Union[str, Any] = np.array(...
6
'''simple docstring''' import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() a_ : Any = logging.get_logger(__name__) a_ : Option...
6
1
"""simple docstring""" import random def __A ( a_ :int , a_ :float , a_ :bool = False) -> dict: __a : dict = {i: [] for i in range(a_)} # if probability is greater or equal than 1, then generate a complete graph if probabili...
160
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __lowercase (...
160
1
'''simple docstring''' 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 __snake_case : Union[str, Any] =...
357
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __snake_case : Optional[Any] = logging.get_logger(__name__) __snake_case : Tup...
18
0
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ....
44
import random from .binary_exp_mod import bin_exp_mod def A ( a_ ,a_=1_000 ) -> Optional[Any]: if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd __UpperCamelCase : List[An...
71
0
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ ): """simple docstring""" A = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def __SCREAMING_SNAKE_CASE ...
368
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_...
57
0
"""simple docstring""" import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def __UpperCAmelCase ( lowercase ): """simple docstring""" _UpperCAmelCase = os.path.join(args.tf_model_dir ,"""paramet...
289
from ..utils import DummyObject, requires_backends class __SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase_ ): _UpperCAmelCase : int = ["transformers", "torch", "note_seq"] def __init__( self : Union[str, Any] , *A : int , **A : Optional[int]...
142
0
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 ModelTesterMixin, ids_te...
352
import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) ...
50
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/r...
247
"""simple docstring""" def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> list[int]: if length <= 0 or not isinstance(lowercase_ , lowercase_ ): raise ValueError("Length must be a positive integer." ) return [n * (2 * n - 1) for n in range(lowercase_ )] if __name__ == "__ma...
247
1
"""simple docstring""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ...
2
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class UpperCAmelCase (_UpperCAmelCase ): """simple docs...
2
1
from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class ...
9
"""simple docstring""" from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
241
0
from math import sqrt def lowerCamelCase__ (__lowerCamelCase ): assert isinstance(_lowerCamelCase, _lowerCamelCase ) and ( number >= 0 ), "'number' must been an int and positive" _SCREAMING_SNAKE_CASE : Optional[Any] = True # 0 and 1 are none pr...
363
from __future__ import annotations import typing from collections import Counter def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__lower...
325
0
"""simple docstring""" from __future__ import annotations class _UpperCAmelCase: def __init__( self , __a=None) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = data _UpperCamelCase = None ...
194
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> bool: """simple docstring""" return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def lowerCamelCase__ ( __snake_case ) -> bool: ...
194
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase : Dict = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""...
25
'''simple docstring''' def lowercase (_A = 1_0_0_0_0_0_0 ): """simple docstring""" _lowerCAmelCase : Any = set(range(3 , _A , 2 ) ) primes.add(2 ) for p in range(3 , _A , 2 ): ...
25
1
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split A : Union[str, Any] = datasets.load_iris() A : int = np.array(data['data']) A : Optional[Any] = np.array(data['target']) A : int = data['target_names'] A ...
6
import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTes...
6
1
def _A ( __magic_name__ ): lowercase__ = len(__A ) while cur > 1: # Find the maximum number in arr lowercase__ = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi lowercase__ = arr[mi::-1] + arr[mi + 1 : len(__A )] # Reverse whole list ...
357
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDC...
201
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a ={ """configuration_blip_2""": [ """BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Blip2Config""", """Blip2QFormerConfig""", """Blip2VisionConfig""",...
73
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 RoFormerTokenizer from .tokenizati...
18
0
import os import re 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 UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_f...
371
import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_ful...
290
0
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] ) -> list[int]: """simple docstring""" UpperCamelCase :List[str] = len(__magic_name__ ) for i in range(__magic_name__ ): for j in range(i + 1 , __magic_name__ ): if numbers[j] < numbers[i...
38
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : str = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''...
57
0
'''simple docstring''' import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput _lowerCAmelCase = logging.getLogger(__name__) if is_torch_t...
357
'''simple docstring''' from ..utils import DummyObject, requires_backends class lowerCAmelCase_( metaclass=SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : int = ['''sentencepiece'''] def __init__( self ,*__UpperCAmelCase ,**__UpperCAmelCase ...
184
0