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''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints...
80
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ...
80
1
"""simple docstring""" import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def SCREAMING_SNAKE_CASE_ ( snake_case : Optional[Any] )-> List[Any]: _lowerCamelCase = os.path.join(args.tf_model_dir ,...
80
"""simple docstring""" from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def SCREAMING_SNAKE_CASE_ ( )-> Any: import os as original_os from os import path as original_path from os import rename as original_rename from os....
80
1
"""simple docstring""" import heapq def a_ ( lowerCamelCase ): UpperCAmelCase__ = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min...
98
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ : int = logging.get_logger(__name__) lowerCAmelCase__ : str = { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/config.json', # ...
98
1
import datasets _snake_case = "\\n@InProceedings{conneau2018xnli,\n author = \"Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Sto...
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
A__ : Tuple = { 'meter': 'm', 'kilometer': 'km', 'megametre': 'Mm', 'gigametre': 'Gm', 'terametre': 'Tm', 'petametre': 'Pm', 'exametre': 'Em', 'zettametre': 'Zm', 'yottametre': 'Ym', } # Exponent of the factor(meter) A__ : Union[str, Any] = { 'm': 0, 'km'...
207
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def a ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): '''simple docstring''' lowercase__ = ('''dense.weight''', '''attention.self.query''', ''...
207
1
'''simple docstring''' import os from datetime import datetime as dt from github import Github lowercase : Any = [ "good first issue", "feature request", "wip", ] def SCREAMING_SNAKE_CASE__ ( ) -> int: _snake_case = Github(os.environ['GITHUB_TOKEN...
160
'''simple docstring''' from __future__ import annotations from collections import namedtuple def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> tuple: _snake_case = namedtuple('result' , 'name value' ) if (voltage, current, power).count(0 ...
160
1
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=lowercase_ ) class UpperCamelCase ( lowercase_ ): lowercase = field(default='a...
213
"""simple docstring""" __SCREAMING_SNAKE_CASE =[ "DownloadConfig", "DownloadManager", "DownloadMode", "StreamingDownloadManager", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloa...
213
1
"""simple docstring""" import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTeste...
2
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, ...
2
1
'''simple docstring''' from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def __lowerCamelCase ( lowerCAmelCase_ = True , *lowerCAmelCase_ , **lowerCAmelCase_ ) -> Dict: if not is_tqd...
89
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): ...
89
1
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class __lowercase (UpperCamelCase__ , unittes...
368
from math import pow def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,) -> tuple[int, int]: if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 ...
176
0
'''simple docstring''' import inspect import unittest class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Optional[Any] ): try: import diffusers # noqa: F401 except ImportError: ...
63
from jiwer import compute_measures import datasets lowerCAmelCase : Tuple = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation...
253
0
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets UpperCamelCase = datasets.logging.get_logger(__name__) UpperCamelCase = '\\n@inproceedings{bleurt,\n title={BLEURT: Learning Robust Metrics for Text Generation},...
221
import argparse from collections import defaultdict def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : int ): """simple docstring""" l...
221
1
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask ...
296
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class lowercase_ ( UpperCamelCase_ ): """simple docstring""" UpperCAmelCase_ : str = (DDPMScheduler,) def SCREAMING_SNAKE_CASE_ ( self , **__SCREA...
338
0
from math import isqrt def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __lowerCamelCase, __lo...
362
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutp...
325
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 UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {'''vocab_file''': '''vocab.j...
195
'''simple docstring''' import math def UpperCAmelCase_ ( __lowercase : int ) -> bool: '''simple docstring''' return math.sqrt(__lowercase ) * math.sqrt(__lowercase ) == num def UpperCAmelCase_ ( __lowercase : int ) -> ...
22
0
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class __A( datasets.BuilderConfig ): snake_case_ = None class __A( datasets.Arr...
33
from __future__ import annotations def __lowerCAmelCase ( a__ , a__ = None ) -> list[list[str]]: __a = word_bank or [] # create a table __a = len(a__ ) + 1 __a = [] for _ in range(a__ ): table.append([] ) # seed value...
33
1
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowerCAmelCase__ : List[str] = False try: lowerCAmelCas...
143
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_te...
143
1
'''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.models.aut...
183
'''simple docstring''' import re import string import numpy as np import datasets SCREAMING_SNAKE_CASE__ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' SCREAMING_SNA...
183
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import t...
103
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 transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def UpperCamelCase( __UpperCamelCase : List[str] ): ...
103
1
"""simple docstring""" from __future__ import annotations def __lowercase ( _a , _a , _a , ): if (stress, tangential_force, area).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif stress < 0: raise ValueError('''S...
155
"""simple docstring""" import os def __lowercase ( _a ): snake_case_ : Tuple = len(grid[0] ) snake_case_ : Optional[int] = len(_a ) snake_case_ : Union[str, Any] = 0 snake_case_ : Union[str, Any] = 0 snake_case_ : L...
155
1
'''simple docstring''' from __future__ import annotations import typing from collections import Counter def _UpperCamelCase ( __A ) -> typing.Counter[int]: '''simple docstring''' UpperCamelCase__ = Counter() for base in range(1 , max_perime...
80
'''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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, ...
80
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCAmelCase : Optional[int] = { "configuration_data2vec_audio": ["DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecAudioConfig"], "configura...
293
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy __UpperCAmelCase : str = logging.get_logger(__name__) ...
293
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
300
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils imp...
300
1
import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.util...
368
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetCo...
81
0
"""simple docstring""" from __future__ import annotations from collections import namedtuple def __A ( a_ :float , a_ :float , a_ :float) -> tuple: __a : Dict = namedtuple('''result''' , '''name value''') if (voltage, cu...
160
"""simple docstring""" A = 9.80665 def __A ( a_ :float , a_ :float , a_ :float = g) -> float: if fluid_density <= 0: raise ValueError('''Impossible fluid density''') if volume < 0: raise ValueError('''Impossible Obj...
160
1
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_...
369
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase: Any = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfi...
96
0
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterM...
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A , A ) -> list[list[int]]: """simple docstring""" lowercase__ = [] create_all_state(1 , A , A , [] , A ) return result def _SCREAMING_SNAKE_CASE ...
2
1
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 Ro...
14
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import (...
14
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any =logging.get_logger(__name__) A__ : int ={ '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''', } ...
70
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_ver...
176
0
'''simple docstring''' import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.co...
311
'''simple docstring''' import argparse import os 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_task_guides.py lowercase : Any = 'src/transform...
311
1
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" A__ = np.max(UpperCamelCase__ , axis=-1 , keepdims=UpperCamelCase__ ) A__ = ...
221
"""simple docstring""" from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState ...
221
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { "...
212
"""simple docstring""" import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class _lowerCamelCase ( a_ ): # to overwrite at feature extractactor spe...
212
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __magic_name__ = { "configuration_mvp": ["MVP_PRETRAINED_CONFIG_ARCHIVE_MAP", "MvpConfig", "MvpOnnxConfig"], "tokenization_mvp": ...
100
"""simple docstring""" import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL UpperCamelCase : Union[str, Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def ...
316
0
'''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 AutoFeatureExtractor, WavaVecaFeatureExtractor from tr...
358
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' pass class lowerCAmelCase_ : '''simple docstring''' def __init__( ...
334
0
"""simple docstring""" import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_model...
33
"""simple docstring""" import argparse import os import re import packaging.version __A : List[str] = '''examples/''' __A : int = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), ...
33
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertC...
352
import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef lowerCamelCase__ = ( '''This metric will be removed from the library soon, metrics sh...
22
0
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class a ( unittest.TestCase ): def UpperCamelCa...
183
"""simple docstring""" import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem _SCREAMING_SNAKE_CASE : Any = importlib.util.find...
183
1
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import...
51
import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, ...
51
1
"""simple docstring""" def lowercase (snake_case__ : int = 600_851_475_143 ) -> int: '''simple docstring''' try: lowerCAmelCase = int(snake_case__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be ...
155
"""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 To...
155
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a : List[Any] = { """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100On...
338
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule a : Optional[int] = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: ...
338
1
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) lowerCAmelCase__ :Dict = str(bin(_SCREAMING_SNAKE_CASE ) )[2:...
293
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _S...
293
1
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _snake_case ( a__...
283
'''simple docstring''' import numpy class _snake_case : def __init__( self , _lowerCamelCase , _lowerCamelCase): UpperCAmelCase__ : Dict = input_array # Random initial weights are assigned where first argument is t...
283
1
"""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...
16
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in ...
81
0
from __future__ import annotations class lowercase : def __init__( self ,A__): lowercase = data lowercase = None lowercase = None def UpperCamelCase ( lowerCAmelCase__ ): # In Order traversal ...
97
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable lowercase__ :Union[str, Any] = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if...
97
1
"""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
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ = {"""configuration_vit_msn""": ["""VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMSNConfig"""]} try: if not is_...
96
0
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : Dict = logging.get_logger(__name__) lowercase__ : Any = { """microsoft/xprophetnet-large-...
289
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase__ : Dict = { """configuration_falcon""": ["""FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FalconCon...
289
1
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 RobertaTokenizer ...
14
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" A__ = args.pruning_method A__ = ar...
14
1
"""simple docstring""" from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _lowerCAmelCase ( ...
357
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ : str = { '''configuration_vision_encoder_decoder''': ['''VisionE...
248
0
'''simple docstring''' import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert im...
311
'''simple docstring''' from collections.abc import Generator from math import sin def lowercase ( __magic_name__ ): '''simple docstring''' if len(__magic_name__ ) != 32: raise ValueError("Input must be of length 32" ) UpperCAmelCase : Un...
311
1
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature f...
367
'''simple docstring''' def _lowerCAmelCase ( lowerCamelCase_ : int = 6_0_0_8_5_1_4_7_5_1_4_3 ): try: __lowercase = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n ...
217
0
from __future__ import annotations import math lowerCamelCase__ = """2020.9.26""" lowerCamelCase__ = """xcodz-dot, cclaus, dhruvmanila""" def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_C...
212
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__ ( __magic_name__ ): l...
212
1
from collections import deque from .hash_table import HashTable class lowercase ( SCREAMING_SNAKE_CASE__ ): def __init__( self ,*A__ ,**A__): super().__init__(*A__ ,**A__) def A__ ( self ,A__ ,A__): lowercase ...
367
from __future__ import annotations from decimal import Decimal from numpy import array def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works fo...
97
0
'''simple docstring''' import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' def ...
37
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_availabl...
334
0
'''simple docstring''' from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_T...
366
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _A : Union[str, Any] =logging.get_logger(__name__) _A : List[Any] ={ '''SenseTime/deformabl...
129
0
from __future__ import annotations import math from collections.abc import Callable def lowerCamelCase__ ( snake_case_ : Callable[[int | float], int | float] , snake_case_ : int | float , snake_case_ : int | float , snake_case_ : int = 100 ...
24
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info()...
22
0
# 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 by app...
97
import numpy as np import datasets lowercase__ :Dict = "\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C....
97
1
import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __snake_case : def __init__( self : int , ...
51
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 diffusers.schedulers.s...
51
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_ro...
351
"""simple docstring""" import argparse import os import re lowercase__ = """src/transformers""" # Pattern that looks at the indentation in a line. lowercase__ = re.compile(r"""^(\s*)\S""") # Pattern that matches `"key":" and puts `key` in group 0. lowercase__ = re.compile(r"""^\s*\...
161
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase__ : Optional[int] = { '''configuration_m2m_100''': ['''M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''M2M100Config''', '''M2M100OnnxConfig'''], '...
338
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class lowercase_ ( UpperCamelCase_ ): """simple doc...
338
1
import random def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: list , lowerCAmelCase: int ) -> tuple: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Dict = [], [], [] for element in data: if element < pivot: less...
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 # # Unless required by ap...
189
1
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_tex...
283
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { '''edbeeching/decision-transformer-gym-hopper-medium''': ( '''https://huggingface.co/edbeeching/decision-transformer-gy...
283
1
import math def a_ ( __lowercase : Optional[int] ) -> Tuple: if not isinstance(_A , _A ): _snake_case = f'''Input value of [number={number}] must be an integer''' raise TypeError(_A ) if number < 1: _snake_case = f'''Input value of [numbe...
358
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, ImageClassifierOutputWit...
130
0
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_...
97
'''simple docstring''' import csv import tweepy # Twitter API credentials __snake_case = '''''' __snake_case = '''''' __snake_case = '''''' __snake_case = '''''' def a ( __a ) -> None: '''simple docstring''' UpperCame...
97
1
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType ...
360
"""simple docstring""" class _A : def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" lowercase = None lowercase = None l...
32
0
"""simple docstring""" import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from .....
289
"""simple docstring""" from math import pow def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,): """simple docstring""" if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solution...
289
1
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __A ='''.''' # Internal TensorFlow ops that can be safely ignored (mostly...
367
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A ={ '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', ...
47
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer a : Dict = logging.get_logger(__name__) ...
114
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, to...
248
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase__ : Optional[int] = { 'configuration_bigbird_pegasus': [ 'BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP', ...
164
'''simple docstring''' def UpperCAmelCase ( a_ , a_ ) -> int: """simple docstring""" A_ : int = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): A_ : Tuple = n - k # Calculate...
164
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __magic_name__ = { "configuration_chinese_clip": [ "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "ChineseCLIPConfig", ...
100
"""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, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditio...
217
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, Bi...
363
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 ...schedulers import DDIMScheduler, DDPMSchedule...
34
0
"""simple docstring""" import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter A__ ...
144
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: ...
97
0
'''simple docstring''' from typing import TYPE_CHECKING from ..utils import _LazyModule UpperCamelCase = { '''config''': [ '''EXTERNAL_DATA_FORMAT_SIZE_LIMIT''', '''OnnxConfig''', '''OnnxConfigWithPast''', '''OnnxSeq2SeqConfigWithPast''', ...
334
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' ...
334
1
"""simple docstring""" import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class _UpperCamelCase ( unittest.TestCase ): '''simple d...
57
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 lowerCamelCase__ ( lowerCamelCase__): '''simp...
129
0
"""simple docstring""" import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokeniz...
32
"""simple docstring""" def UpperCAmelCase__ ( lowerCAmelCase__ :list[list] ) -> list[list]: '''simple docstring''' lowercase = current_set.copy() for row_index, row in enumerate(lowerCAmelCase__ ): lowercase = row[0]...
32
1
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable __snake_case = {'''configuration_dpt''': ['''DPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''...
97
'''simple docstring''' __snake_case = 65521 def a ( __a ) -> int: '''simple docstring''' UpperCamelCase__ :Tuple = 1 UpperCamelCase__ :Any = 0 for plain_chr in plain_text: UpperCamelCase__ :List[str] = (a + o...
97
1
"""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, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers....
254
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from...
254
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : float ): """simple docstring""" return 10 - x * x def UpperCAmelCase__ (snake_case__ : float , snake_case__ : float ): """simple docstring""" if equation(snake_cas...
64
'''simple docstring''' import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_model...
161
0
"""simple docstring""" import cva import numpy as np class SCREAMING_SNAKE_CASE_ : """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__): if k in (0.04, 0.06): __SCREAMING_SNAKE_CASE = k __SCREAMING_SNAKE_CASE = windo...
255
"""simple docstring""" import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) __magic_name__ = { ...
255
1
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resi...
189
import numpy as np def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> np.array: return 1 / (1 + np.exp(-vector )) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> np.array: return vector * sigmoid(1.7_0_2 * vector ) if __name__ =...
189
1
def lowerCAmelCase_ ( snake_case_ ): _A : str = [0] * len(snake_case_ ) _A : Optional[int] = [] _A : List[Any] = [] _A : Dict = 0 for values in graph.values(): for i in val...
343
# Copyright (c) 2021-, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
343
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/li...
93
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 snake_case__(_UpperCamelCase , _UpperCamelCase ): """simple docstring""" @register_to_config ...
130
0
import torch from torch import nn class SCREAMING_SNAKE_CASE_ ( nn.Module ): def __init__( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : List[str] , lowerCamelCase_ : int=1 , lowerCamelCase_ : ...
366
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore _SCREAMING_SNAKE_CASE = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" _SCREAMING_SNAKE_CASE = [file for file in...
165
0
'''simple docstring''' def UpperCamelCase_ ( ) -> str: """simple docstring""" _UpperCAmelCase : Dict = 0 for i in range(1 , 1_001 ): total += i**i return str(_UpperCAmelCase )[-10:] if __name__ == "__main__": print(s...
31
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ ...
32
0
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_comm...
110
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class ...
110
1
"""simple docstring""" def _snake_case ( _snake_case : int ): if not isinstance(_UpperCamelCase , _UpperCamelCase ): lowerCAmelCase : int = f'''Input value of [number={number}] must be an integer''' raise TypeError(_UpperCamelCase ) if number ...
60
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCamelCase : Union[str, Any] = TypeVar("KT") lowerCamelCase : Dict = TypeVar("VT") class A__ ( Generic[KT, VT] ): def __init__( self...
47
0
"""simple docstring""" import csv import tweepy # Twitter API credentials SCREAMING_SNAKE_CASE : Optional[Any] = '''''' SCREAMING_SNAKE_CASE : Optional[int] = '''''' SCREAMING_SNAKE_CASE : List[str] = '''''' SCREAMING_SNAKE_CASE : Union[str, Any] = '''''' def low...
350
"""simple docstring""" def lowercase ( ) ->int: """simple docstring""" return [ a * b * (1_000 - a - b) for a in range(1 , 999 ) for b in range(_snake_case , 999 ) if (a * a + b * b == (1_000 - a - b) ** 2) ][0] if __name__ == "__main__": p...
24
0
'''simple docstring''' from __future__ import annotations def _A ( lowercase__ ): lowercase__ = 2 lowercase__ = [] while i * i <= n: if n % i: i += 1 else: n //= i ...
164
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A = logging.get_logger(__name__) __A = {"vocab_file": "spm_char.mod...
164
1
"""simple docstring""" import sys from pathlib import Path __magic_name__ = Path(__file__).resolve().parents[3] / "src" sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy impor...
354
"""simple docstring""" def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): while b: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = b, a % b return a def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): return a if b == 0 else euclidean_gcd_r...
255
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, PreTrainedTokenizerBase, TensorType...
12
'''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, get_resize_output_image_size, normalize, rescale, resize,...
34
0
'''simple docstring''' import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_c...
356
'''simple docstring''' from __future__ import annotations def __UpperCamelCase ( _UpperCAmelCase ): if not nums: raise ValueError("List is empty" ) return sum(_UpperCAmelCase ) / len(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
37
0
import random def __snake_case ( _lowerCAmelCase : str , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple ) -> Optional[int]: A_ : Union[str, Any] = a[left_index] A_ : int = left_index + 1 for j in range(left_index + 1 , _lowerCAmelCa...
300
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = (DDPMScheduler,) def SCREAMING_SNAKE_CASE ( self :Union[s...
300
1
'''simple docstring''' import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from t...
31
'''simple docstring''' import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import lo...
31
1
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension fro...
32
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" a_ : Optional[Any] = HfArgumentParser(__A ) a_ : Optional[int] = parser.par...
32
1
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increase...
359
'''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, EulerAn...
249
0
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, T...
254
'''simple docstring''' import qiskit def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum...
254
1
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__ : Optional[Any] = log...
352
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed fro...
330
0
"""simple docstring""" def lowercase__ ( _UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('Input value must be an \'int\' type' ) lowercase : str = 0 ...
255
"""simple docstring""" def lowercase__ ( _UpperCAmelCase , _UpperCAmelCase ) -> Dict: '''simple docstring''' _enforce_args(_UpperCAmelCase , _UpperCAmelCase ) if n == 0: return 0 lowercase : Tuple = float('-inf' ...
255
1
'''simple docstring''' def _lowerCAmelCase ( lowercase ) -> Optional[int]: __lowerCAmelCase = [] __lowerCAmelCase = set({"""(""", """[""", """{"""} ) __lowerCAmelCase = set({""")""", """]""", """}"""} ) __lowerCAmelCase = {"""{"""...
46
'''simple docstring''' import warnings from .generation import TFGenerationMixin class _UpperCAmelCase ( lowerCAmelCase_ ): # warning at import time warnings.warn( """Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will """ ...
46
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer ...
182
'''simple docstring''' import math def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> float: if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of initia...
321
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Union[str, Any] = logging.get_logger(__name__) A__ : Optional[int] = { '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/...
371
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''p...
0
0