code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import 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, is_vision_available f...
99
"""simple docstring""" from math import isqrt, loga def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> list[int]: '''simple docstring''' lowercase_ = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prim...
136
0
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCAmelCase : List[Any] = TypeVar("""KT""") lowerCAmelCase : Optional[int] = TypeVar("""VT""") class UpperCamelCase__ ( Generic[KT,...
25
'''simple docstring''' from math import isqrt def lowercase (_A ): """simple docstring""" return all(number % divisor != 0 for divisor in range(2 , isqrt(_A ) + 1 ) ) def lowercase (_A = 1_0**6 ): ...
25
1
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from ...
149
'''simple docstring''' 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_t...
166
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase =logging.get_logger(__name__) UpperCAmelCase ...
362
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase =logging.get_logger(__name__) UpperCAmelCase ={ "distilbert-base-unca...
77
0
'''simple docstring''' from __future__ import annotations def _lowerCamelCase ( lowercase : dict , lowercase : str ) -> set[str]: _a , _a = set(lowercase ), [start] while stack: _a = stack.pop() explored.add(lowerca...
63
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : Optional[int] = { 'ut/deta': 'https://huggingfa...
63
1
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin cl...
283
'''simple docstring''' import os import unicodedata 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 SPIECE_UNDERLINE, logging __A =logging.get_l...
283
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { '''configuration_blip_2''': [ '''BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Blip2Config''', '''Blip2QFormerConfig''', '''Blip2Vis...
5
from __future__ import annotations import os from collections.abc import Mapping a_ = tuple[int, int] class lowercase__ : def __init__( self , __UpperCAmelCase , __UpperCAmelCase )-> None: '''simple docstring''' lowerCAmelCase__ = ...
340
0
"""simple docstring""" lowercase__ : Union[str, Any] = { """meter""": """m""", """kilometer""": """km""", """megametre""": """Mm""", """gigametre""": """Gm""", """terametre""": """Tm""", """petametre""": """Pm""", """exametre""": """Em""", """...
289
"""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_mod...
289
1
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import ...
206
"""simple docstring""" UpperCAmelCase__ = [ [0, 1_6, 1_3, 0, 0, 0], [0, 0, 1_0, 1_2, 0, 0], [0, 4, 0, 0, 1_4, 0], [0, 0, 9, 0, 0, 2_0], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ,lowercase ): ...
289
0
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lic...
128
"""simple docstring""" from ...processing_utils import ProcessorMixin class _a ( _lowerCAmelCase ): UpperCamelCase = ['''image_processor''', '''feature_extractor'''] UpperCamelCase = '''TvltImageProcessor''' UpperCamelCase = '''TvltFe...
128
1
import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py _lowerCamelCase : Dict = "src/diffusers" # Matches is_xxx_available() _lowerCamelCase : Any = re.compile(...
336
"""simple docstring""" import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPI...
247
0
'''simple docstring''' from __future__ import annotations from statistics import mean def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _snake_case = [0] * no_of_processes _snake_case = [0] * no_of_processes ...
358
'''simple docstring''' import qiskit def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _snake_case = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register _snake_case = qiskit.QuantumCircui...
270
0
'''simple docstring''' import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": lowerCAmelCase: Optional[Any] = argparse.ArgumentParser( description=( 'Extraction some layers of the full RobertaForM...
297
from math import factorial __snake_case = {str(digit): factorial(digit) for digit in range(10)} def _A ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('''Parameter number must be int''' ...
259
0
import qiskit def lowerCAmelCase__ ( lowerCamelCase_ : int = 2): '''simple docstring''' lowerCAmelCase__ : Any = qubits # Using Aer's simulator lowerCAmelCase__ : Any = qiskit.Aer.get_backend('''aer_simulator''') # Creating a Qu...
94
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_G...
94
1
'''simple docstring''' def __magic_name__( lowerCamelCase, lowerCamelCase): return abs(lowerCamelCase) if a == 0 else greatest_common_divisor(b % a, lowerCamelCase) def __magic_name__( lowerCamelCase, lowerCamelCase): while y: # --> when y=0 then loop will terminate and return...
174
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize,...
174
1
from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=__snake_case ): '''simple docstring''' A__ : List[Any] = ["keras_nlp"] def __init__( self: int ,*lowerCamelCase_: Optional[int] ,**lowerCamelCase_: ...
368
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { '''junnyu/roformer_chinese_small''': '''https://...
59
0
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase_ : """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ ...
25
"""simple docstring""" UpperCAmelCase__ : Any = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transform...
25
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 diffusers.pipelines....
92
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-...
92
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def UpperCAmelCase__ (lowerCAmelCase_ = 100 ): ...
54
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_dimension_format, ) from ...
328
0
"""simple docstring""" import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.mode...
289
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : int ): # test for the above condition ...
289
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' ...
45
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE__ ( metaclass=SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __lowerCamelCase : List[str] = ["torch", "transformers", "onnx"] def __init__( self, *lowerCamelCase__, **lowerCam...
116
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "Intel/dpt-large": "https://huggingface.co/Intel/dpt-large/resolve/main/config.json", ...
367
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def lowerCAmelCase__ ( _UpperCamelCase : int = 8 ) -> str: """simple docstring""" snake_case ...
149
0
from ..utils import DummyObject, requires_backends class __SCREAMING_SNAKE_CASE( metaclass=a_ ): _UpperCAmelCase = ["torch", "transformers", "onnx"] def __init__( self: Optional[Any] , *UpperCamelCase: Union[str, Any] , **UpperCamelCase: List[A...
307
from typing import TYPE_CHECKING from ..utils import _LazyModule __UpperCamelCase : Tuple = { """config""": [ """EXTERNAL_DATA_FORMAT_SIZE_LIMIT""", """OnnxConfig""", """OnnxConfigWithPast""", """OnnxSeq2SeqConfigWithPast""", """Patc...
307
1
"""simple docstring""" def lowercase_ ( __UpperCAmelCase ) -> Any: lowerCAmelCase__ : str = len(__UpperCAmelCase ) for i in range(length - 1 ): lowerCAmelCase__ : Optional[int] = i for k in range(i + 1 , __UpperCAmelCase ): ...
367
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor _A = logging.get_logger(__name__) class _lowerCamelCase ( a_ ): def __init__( self : Union[str, Any] , *UpperCamelCase : int ...
212
0
'''simple docstring''' # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def snake_case_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any] ) -> Tuple: Up...
23
from typing import TYPE_CHECKING from ...utils import _LazyModule lowercase = {"processing_wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"]} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys lowercase = _LazyModule(__name__, globals...
178
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Dict = { ""...
352
"""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, req...
215
0
lowercase__ :dict[str, float] = { "joule": 1.0, "kilojoule": 1000, "megajoule": 100_0000, "gigajoule": 10_0000_0000, "wattsecond": 1.0, "watthour": 3600, "kilowatthour": 360_0000, "newtonmeter": 1.0, "calorie_nutr": 4186.8, "kilocalorie_nutr": 418_6800.00, "electronvol...
101
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_token...
101
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import DebertaVaConfig, 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, ...
56
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : int = { """^""": 3, """*""": 2, """/""": 2, ...
56
1
'''simple docstring''' import numpy class lowerCamelCase_ : def __init__( self : Dict , _A : Optional[int] , _A : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : List[str] = inp...
181
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClass...
127
0
"""simple docstring""" from math import pi, sqrt def lowercase__(A ) ->float: """simple docstring""" if num <= 0: raise ValueError("math domain error" ) if num > 171.5: raise OverflowError("math ran...
354
"""simple docstring""" import os from pathlib import Path def lowercase__() ->List[Any]: """simple docstring""" from torch.utils.cpp_extension import load lowercase__ : Any= Path(A ).resolve().parent.parent.parent / "kerne...
150
0
import random def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> int: '''simple docstring''' UpperCAmelCase = num - 1 UpperCAmelCase = 0 while s % 2 == 0: UpperCAmelCase = s // 2 t += 1 for _ in range(5 ): UpperCAmelCase = r...
273
'''simple docstring''' import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers....
298
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : Optional[Any] = logging.get_logger(__name__) __lowerCamelCase : Dict = { """tiiuae/falcon-40b""": """https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.js...
366
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() __lowerCamelCase : int = logging.get_logger(__name__) __lowerCamelCase : Tuple = {name: getattr...
204
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ : str = logging.get_logger(__name__) UpperCamelCase__...
112
'''simple docstring''' import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn #...
239
0
"""simple docstring""" import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_comm...
86
"""simple docstring""" def lowercase__ ( snake_case_ :int , snake_case_ :int , snake_case_ :int ): __UpperCAmelCase = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowercase__ ( ...
86
1
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder a_ = datasets.utils.logging.get_logger(__name__) class _UpperCamelCase ( folder_based_builder.FolderBasedBuilderConfig ): '''simple docstri...
76
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_mode...
238
0
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def ...
19
from sklearn.metrics import matthews_corrcoef import datasets a__ : Optional[Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into accou...
19
1
import re def __lowercase ( __lowerCAmelCase : str ): if len(re.findall('[ATCG]' , __lowerCAmelCase ) ) != len(__lowerCAmelCase ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG' , 'TAGC' ) ) if __name__...
240
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 snake_case : Union[str, Any] = logging.get_logger(__name__) snake_case : ...
240
1
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowercase__ ( _UpperCAm...
169
from __future__ import annotations class lowercase__ : def __init__( self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = text, pattern SCREAMING_SNAKE_CA...
169
1
import unittest import numpy as np from transformers.testing_utils import is_flaky, 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(): imp...
82
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): f...
115
0
'''simple docstring''' def _lowerCAmelCase ( lowercase , lowercase ) -> Optional[Any]: if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) __lowerCAmelCase = str(bin(A__ ) )[2:] # remove the leading "0b" __l...
357
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : List[Any] = {"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]} ...
46
0
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( '''split_dict''' , [ SplitDict(), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1_337 , num_examples=42 , dataset_name='''my_dataset'''...
182
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : List[str] ={ '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''',...
53
0
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils...
369
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 OnnxPipeli...
293
0
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Any = False class lowercase_ ( unittest.Test...
80
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, ...
185
0
"""simple docstring""" import re import string import numpy as np import datasets lowerCAmelCase_ : Union[str, Any] = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' lowerCA...
358
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
248
0
from __future__ import annotations from math import pi def lowerCamelCase__ ( __lowerCamelCase : float , __lowerCamelCase : float , __lowerCamelCase : float ): if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("""One and on...
114
from functools import lru_cache @lru_cache def lowerCamelCase__ ( __lowerCamelCase : int ): if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": i...
114
1
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets lowercase__ :str = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n boo...
368
import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowercase__ ...
97
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case : Dict =logging.get_logger(__name__) __snake_case : Optional[int] ={ 'facebook/xlm-roberta-xl'...
129
# 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/licenses/LICENSE-2.0 # # Unl...
129
1
import datasets from .evaluate import evaluate __SCREAMING_SNAKE_CASE : List[Any] = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv pre...
368
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Autofor...
284
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPEN...
171
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, ...
171
1
'''simple docstring''' import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import Fla...
18
'''simple docstring''' import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules i...
18
1
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, ...
19
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 =logging....
19
1
"""simple docstring""" from cva import destroyAllWindows, imread, imshow, waitKey def lowerCamelCase (a_ :Optional[int]) -> Tuple: lowercase :List[Any] = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i ...
353
"""simple docstring""" import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = '...
172
0
'''simple docstring''' def UpperCamelCase ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int ): if principal <= 0: raise Exception("Principal borrowed must be > 0" ) if rate_per_annum < 0: ra...
237
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def UpperCamelCase ( _lowerCamelCase : list[list[float]] ): A__ = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implem...
237
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a__ : Optional[int] = {} try: if not is_sentencepiece_available(): raise Option...
364
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ ...
19
0
'''simple docstring''' def __lowerCamelCase ( A__ ) -> bool: """simple docstring""" UpperCamelCase = 0 for ch in input_str: UpperCamelCase = ord(A__ ) UpperCamelCase = pow(2 , A__ ) # If we already turned on bit f...
28
"""simple docstring""" # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for...
46
0
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( Efficien...
130
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, ...
130
1
import unittest from typing import Dict, List, Optional, Union 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_...
92
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_comm...
255
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_si...
5
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ...
5
1
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class a__ ( _UpperCAmelCase ): ...
68
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Im...
340
0
from __future__ import annotations def __snake_case ( _lowerCAmelCase : int , _lowerCAmelCase : int ) -> list[str]: if partitions <= 0: raise ValueError("partitions must be a positive number!" ) if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_b...
70
import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken ...
70
1
from collections import deque def _a ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" UpperCamelCase__ : List[Any] = len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ : str = deque() UpperCamelCase__ : str = [False for _ in range(SCR...
146
import os import sys __UpperCamelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), "src") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassi...
146
1
_snake_case : str = frozenset( [ 'prompt', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) _snake_case : int = frozenset(['prompt', 'neg...
207
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : Any ) -> Optional[int]: ...
207
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Dict =logging.get_logger(__name__) _A : Any ={ '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''...
41
"""simple docstring""" 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, apply_forward_hook from .modeling_utils import ModelMixin from .vae import D...
144
0
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning t...
279
from math import isclose, sqrt def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> tuple[float, float, float]: """simple docstring""" snake_case_ : Dict = point_y / 4 / point_x snake_case_ : List[str] ...
279
1
from collections import defaultdict from math import ceil, sqrt def _snake_case ( lowerCAmelCase : int = 1_0_0_0_0_0_0 , lowerCAmelCase : int = 1_0 ): """simple docstring""" SCREAMING_SNAKE_CASE_ : defaultdict = defaultdict(lowerCAmelCase ) for outer_width in ra...
18
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 __lowerCamelCase : List[str] = logging.get_logger(__name__) __lowerCamelCase : Tuple ...
18
1
"""simple docstring""" def lowercase ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ): '''simple docstring''' while a != 0: _UpperCAmelCase , _UpperCAmelCase = b % a, a return b def ...
354
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from ...
326
0
"""simple docstring""" import logging from transformers import PretrainedConfig a : Tuple = logging.getLogger(__name__) a : Dict = { '''bertabs-finetuned-cnndm''': '''https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/r...
105
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerat...
252
0
import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' return x + 2 class UpperCamelCase__...
362
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.test...
193
0
'''simple docstring''' import warnings 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 lowercase_ ( ...
80
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A ={ '''configuration_bloom''': ['''BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BloomConfig''', '''BloomOnnxConfig'''], } try: if not is_tokenizers_available(): ...
19
0
from __future__ import annotations from typing import Any class UpperCAmelCase_ : def __init__( self, __a, __a, __a = 0): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : int = row, column _...
300
from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCAmelCase_ ( a): @staticmethod @abstractmethod def snake_case__ ( __a): '''simple docstring''' raise NotImplementedError() @abstractmethod...
300
1
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset from utils import logger class __lowerCAmelCase ( __lowerCamelCase ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' __UpperCamelCase =...
316
import os import unicodedata 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 SPIECE_UNDERLINE, logging A__ = logging.get_logger(__name__) ...
230
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHE...
226
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform fr...
226
1
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesser...
5
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMToke...
5
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 a (_lowerCAmelCase ): """simple docstring""" ...
134
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split _snake_case : Union[str, Any] = datasets.load_iris() _snake_case : Tuple = np.array(data["data"]) _snake_case : int = np.array(data["target"])...
134
1
'''simple docstring''' from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeature...
324
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ : Tuple = { 'configuration_mctct': ['MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MCTCTConfig'], 'feature_extraction_mctct': ['MCTCTFeatur...
324
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase : List[Any] = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCH...
263
"""simple docstring""" from math import factorial UpperCamelCase : List[Any] = {str(d): factorial(d) for d in range(1_0)} def A ( snake_case :int ) -> int: return sum(DIGIT_FACTORIAL[d] for d in str(snake_case ) ) def A ( ) -> int: __Uppe...
263
1
def A ( _lowerCamelCase = 1_000 ): '''simple docstring''' _lowerCAmelCase : str = 1, 1 _lowerCAmelCase : Any = 2 while True: _lowerCAmelCase : str = 0 _lowerCAmelCase : Tuple = ...
36
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase : Optional[Any] ={ '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', ...
223
0
from timeit import timeit def lowerCamelCase__ ( a ) -> int: if number < 0: raise ValueError('''the value of input must not be negative''' ) _A: List[str] = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ ...
301
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, ...
301
1
"""simple docstring""" from __future__ import annotations def _A (__a , __a ) -> list[list[int]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : list[list[int]] = [] create_all_state(1 , __a , __a , [] , __a ) r...
91
'''simple docstring''' from ....utils import logging lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple , __a : int , ...
63
0
from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester fro...
295
import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common...
295
1
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, ...
255
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _UpperCamelCase: List[str] = {} try: if not is_s...
255
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel from diffusers.utils import floa...
353
'''simple docstring''' from typing import Dict from .base import GenericTensor, Pipeline class lowerCamelCase ( lowercase_ ): '''simple docstring''' def lowercase__ ( self : List[str] , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : Dict=None , ...
136
0
'''simple docstring''' import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from tra...
112
import math def snake_case_ ( snake_case , snake_case ) -> float: return math.pow(snake_case , 2 ) - a def snake_case_ ( snake_case ) -> float: return 2 * x def snake_case_ ( snake_case ) -> float: ...
196
0
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig...
357
"""simple docstring""" import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @req...
186
0
from __future__ import annotations from typing import Any def _snake_case( SCREAMING_SNAKE_CASE__ ) -> int: if not postfix_notation: return 0 lowercase : int = {"""+""", """-""", """*""", """/"""} lowercase : list[Any] = ...
20
'''simple docstring''' from collections import defaultdict class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = total # total no of tasks (N) # DP table ...
97
0
import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BA...
358
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, At...
271
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> List[str]: if any(not isinstance(a__ , a__ ) or x < 0 for x in sequence ): raise TypeError('Sequence must be list of non-negative integers' ) for _ in range(len(a__ ) ): for i, (rod_upper, rod_low...
212
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class a_ : """simple d...
313
0
from __future__ import annotations from typing import Generic, TypeVar _UpperCAmelCase : str = TypeVar("""T""") class lowercase ( Generic[T] ): def __init__( self , snake_case ): snake_case_ = data snake_case_ = self ...
200
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 tr...
200
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property ...
16
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : str = { '''configuration_roformer''': ['''ROFORM...
54
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Optional[Any] = {"configuration_mbart": ["MBART...
159
def _UpperCAmelCase (UpperCamelCase_ : str , UpperCamelCase_ : str ): '''simple docstring''' _lowerCAmelCase : str = len(UpperCamelCase_ ) + 1 _lowerCAmelCase : List[Any] = len(UpperCamelCase_ ) + 1 # dp is a 2d matrix where dp[i][j] denotes w...
159
1
"""simple docstring""" import numpy as np def lowerCamelCase_ (UpperCamelCase__ : np.ndarray , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float = 1E-1_2 , UpperCamelCase__ : int = 100 , ): assert np.shape(UpperCamelCase__ )[0] == np.shape(...
263
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowerCAmelCase :str = { 'configuration_squeezebert': [ 'SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SqueezeBertCon...
263
1
import os import pytest from transformers.dynamic_module_utils import get_imports __a = ''' import os ''' __a = ''' def foo(): import os return False ''' __a = ''' def foo(): def bar(): if True: import os return False return bar() ''' __a = '...
350
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, C...
173
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers....
150
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {"vocab_file": "vocab.json"} SCREAMING_S...
150
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, Au...
360
def lowercase_ ( A__ = 1000 ) -> int: """simple docstring""" return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
137
0
"""simple docstring""" def _snake_case ( _snake_case : list ): def merge(_snake_case : list , _snake_case : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) y...
60
"""simple docstring""" import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowerCamelCase__ ( __snake_case, __snake_c...
194
0
'''simple docstring''' import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_STAR...
365
'''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 TFModelTesterMixin, ids_tensor, rando...
52
0
import math def lowerCamelCase_ ( lowerCamelCase__ ): 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 False # All primes n...
19
"""simple docstring""" import os import unicodedata 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 SPIECE_UNDERLINE, logging _lowerCamelCase ...
167
0
import math def __magic_name__ ( __a : int ): '''simple docstring''' return math.sqrt(__a ) * math.sqrt(__a ) == num def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 UpperCamelCase__ ...
178
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, BertTokenizerFas...
178
1
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from path...
86
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, ...
105
0
'''simple docstring''' from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...scheduler...
354
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ , lowerCamelCase_ ): '''simp...
274
0