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
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers...
88
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common imp...
88
1
'''simple docstring''' import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate...
43
'''simple docstring''' def __snake_case( _lowerCAmelCase ) -> int: if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError("""Input value must be an 'int' type""" ) snake_case__ : List[str] = 0 while number: positi...
43
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow,...
227
def snake_case( __magic_name__ , __magic_name__ ) -> float: '''simple docstring''' return price * (1 + tax_rate) if __name__ == "__main__": print(f'''{price_plus_tax(1_00, 0.2_5) = }''') print(f'''{price_plus_tax(1_2_5.5_0, 0.0_5) = }''')
308
0
from __future__ import annotations import time _SCREAMING_SNAKE_CASE : List[str] = list[tuple[int, int]] _SCREAMING_SNAKE_CASE : str = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, ...
218
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, s...
218
1
'''simple docstring''' import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class A__ ( lowerCamelCase...
162
'''simple docstring''' def _lowerCamelCase ( lowercase : str ) -> list: if n_term == "": return [] _a = [] for temp in range(int(lowercase ) ): series.append(F'1/{temp + 1}' if series else "1" ) return series if __name__ == "__main_...
63
0
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __magic_name__ ( self : Optional[int] , lowerCAmelCase...
362
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : Any = '.' # Internal TensorFlow ops tha...
301
0
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't ...
347
"""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_token...
347
1
"""simple docstring""" # Copyright 2021 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-...
368
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : flo...
27
0
'''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 tests...
89
'''simple docstring''' def __lowercase ( __lowercase , __lowercase , __lowercase=False ) -> Union[str, Any]: '''simple docstring''' if isinstance(__lowercase , __lowercase ) and isinstance(__lowercase , __lowercase ): _A =...
79
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __UpperCAmelCase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig'...
103
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines...
103
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_...
274
class A (SCREAMING_SNAKE_CASE ): '''simple docstring''' pass class A (SCREAMING_SNAKE_CASE ): '''simple docstring''' pass class A : '''simple docstring''' def __init__( self : List[Any] ) -> str: """simp...
274
1
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() UpperCAmelCase__...
358
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[Any] = { 'vo...
301
0
import heapq as hq import math from collections.abc import Iterator class lowercase : def __init__( self ,A__): lowercase = str(id_) lowercase = None lowercase = None lowercase = [] lower...
101
import os import pytest from attr import dataclass UpperCAmelCase__ : Optional[int] = """us-east-1""" # defaults region @dataclass class a__ : """simple docstring""" UpperCAmelCase__ : str UpperCAmelCase__ : Union[str, ...
245
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCamelCase ( metaclass=a_ ): """simple docstring""" A : Union[str, Any] = ["torch"] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , *...
345
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( snake_case : list[int | float] , snake_case : int , snake_case : int ) -> int | float: """simple docstring""" if len(snake_case ) =...
345
1
"""simple docstring""" from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder __lowercase = datasets.utils.logging.get_logger(__name__) class _A ( folder_based_build...
40
from __future__ import annotations import math class snake_case__: '''simple docstring''' def __init__( self , __lowercase ) -> None: lowerCAmelCase_ : str = size # approximate the overall size of segment tree with given value ...
262
0
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if len(lowerCamelCase_ ) != len(lowerCamelCase_ ): raise ValueError("""String lengths must match!""" ) _a : Optional[Any] = ...
368
"""simple docstring""" import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.confi...
324
0
__snake_case : List[str] = { """joule""": 1.0, """kilojoule""": 10_00, """megajoule""": 1_00_00_00, """gigajoule""": 10_00_00_00_00, """wattsecond""": 1.0, """watthour""": 36_00, """kilowatthour""": 3_60_00_00, """newtonmeter""": 1.0, """calorie_nutr""": 41_86...
248
import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor _lowerCamelCase =logging.get_logger(__name__) class A__ ( __SCREAMING_SNAKE_CASE): def __init__( self , *__magic_name__ , **__magic_name__ ): warnings.warn( ...
287
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE( metaclass=lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = ['note_seq'] def __init__( self ,*SCREAMING_SNAKE_CASE__ ,**SCREAMI...
358
"""simple docstring""" import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.uti...
239
0
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __lowercase = (720, 1280) # Height, Width __lowercase = (0.4, 0.6) # if height or width lower than this scale, dr...
40
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ = logging.get_logger(__name__) a__ = { """google/efficientnet-b7""": ...
317
0
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :Optional[Any] ) -> Any: # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection __lowerCAmelCase : Any = len(SCREAMING_SNAKE_CASE ) __lowerCAmelCa...
369
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers...
232
0
def A__ ( SCREAMING_SNAKE_CASE__) -> list: if len(SCREAMING_SNAKE_CASE__) <= 1: return lst __snake_case: Any = 1 while i < len(SCREAMING_SNAKE_CASE__): if lst[i - 1] <= lst[i]: i += 1 else: __snake_case , __snake_case: Union[str, Any] = l...
111
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class __snake_case ( unittest.TestCase , __lowerCamelCase ): '''simple docstring''' def UpperCAmelCase__ ( self : Union[str, Any] ): __sna...
111
1
'''simple docstring''' import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusi...
6
'''simple docstring''' from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def a_ ( ) -> Tuple: """simple docstring""" lowerCamelCase_ ={ '''repo_name''': ['''t...
6
1
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES __snake_case = logging.get_logger(__name__) __snake_case = OrderedDic...
203
"""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
0
import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_uti...
245
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
245
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case__ : str = logging.get_logger(__name__) snake_case__ : Dict = { '''edbeeching/decision-transformer-gym-hopper-medium''': ( '''https://huggingface.co/edbeeching/dec...
60
"""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 transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformer...
60
1
"""simple docstring""" import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase ...
133
"""simple docstring""" import re from filelock import FileLock try: import nltk lowerCAmelCase__ = True except (ImportError, ModuleNotFoundError): lowerCAmelCase__ = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt...
133
1
from math import pi, sqrt def A_ ( A__ ) -> float: if num <= 0: raise ValueError('math domain error' ) if num > 1_71.5: raise OverflowError('math range error' ) elif num - int(A__ ) not in (0, 0.5): raise NotImplementedError('num mus...
99
class UpperCAmelCase : '''simple docstring''' def __init__( self : Dict ): """simple docstring""" snake_case_ = {} # Mapping from char to TrieNode snake_case_ = False ...
187
0
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import Onnx...
352
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case_ ( __lowercase ): A_ = ['image_processor', 'tokenizer'] A_ = 'ChineseCLIPImageProcessor' A_ = ('BertTokenizer'...
232
0
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib UpperCAmelCase_ : List...
32
def _UpperCamelCase ( snake_case__ ) -> int: __UpperCAmelCase : Union[str, Any] = abs(snake_case__ ) __UpperCAmelCase : Dict = 0 while n > 0: res += n % 10 n //= 10 return res def _UpperCamelCas...
157
0
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class A__ : lowercase = None def snake_case_ ( self ) -> List[Any]: '''simple docstring''' A_ = self.feature_extraction_class(**self.fea...
360
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) __lowerCamelCase...
101
0
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_sim...
90
'''simple docstring''' from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowercase : str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowercase : list[int] = [ord(letter)...
42
0
class UpperCAmelCase_ : # Public class to implement a graph '''simple docstring''' def __init__( self , _A , _A , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = row __SCREAMING_SNAKE_CASE =...
358
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers c...
118
0
"""simple docstring""" from collections.abc import Sequence from queue import Queue class lowercase: '''simple docstring''' def __init__( self: Dict, a_: Dict, a_: Any, a_: int, a_: Optional[Any]=None, a_: int=None ): ...
64
"""simple docstring""" from math import factorial A_ = {str(d): factorial(d) for d in range(10)} def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def UpperCAmelCas...
64
1
"""simple docstring""" def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> int: if len(__lowerCamelCase ) <= 1: return [tuple(__lowerCamelCase )] lowerCAmelCase__ : str = [] def generate(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )...
360
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> str: return "".join([hex(SCREAMING_SNAKE_CASE_ )[2:].zfill(2 ).upper() for byte in list(SCREAMING_SNAKE_CASE_ )] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> bytes: # Check data validity, following RFC3...
307
0
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) class lowerCAmelCase__ ( lowercase ): '''simple docstring''' lower...
96
"""simple docstring""" def _snake_case ( lowercase__ ): stooge(lowercase__ , 0 , len(lowercase__ ) - 1 ) return arr def _snake_case ( lowercase__ , lowercase__ , lowercase__ ): if i >= h: return ...
96
1
import os import time import numpy as np import onnxruntime as ort lowerCamelCase : int = "1" lowerCamelCase : int = "0" lowerCamelCase : Union[str, Any] = "1" lowerCamelCase : List[Any] = ort.SessionOptions() lowerCamelCase : Opt...
208
def _SCREAMING_SNAKE_CASE ( lowercase : str , lowercase : int ): '''simple docstring''' return [sentence[i : i + ngram_size] for i in range(len(lowercase ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod ...
208
1
class __lowerCAmelCase : def __init__( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = val __lowerCamelCase = None __lowerCamelCase = None def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''...
330
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, AttnProcessor from .modelin...
330
1
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCAmelCase_ = pd.read_csv('sample_data.csv', header=None) UpperCAme...
352
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.j...
61
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax impor...
206
'''simple docstring''' import re def a ( lowerCamelCase__ ): '''simple docstring''' return [char.split() for char in re.split(r"""[^ a-z A-Z 0-9 \s]""" , str_ )] def a ( lowerCamelCase__ ): '''simple docstring''' A_ : Optional[int] = split_input(str_...
206
1
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class UpperCAmelCase_ ...
230
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels SCREAMING_SNAKE_CASE = object() # For specifying empty leaf dict `{}` SCREAMING_SNAKE_CASE = object() ...
230
1
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): im...
232
from math import isqrt, loga def UpperCAmelCase_ ( __lowerCAmelCase ) -> list[int]: __lowercase : Optional[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 , ...
156
0
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipe...
100
"""simple docstring""" import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict _a = namedtuple( """_TestComma...
100
1
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowercase__ ( __lowerCamelCase ): '''simple docstring''' @staticmethod @abstractmethod def UpperCamelCase__ ( __magic_name__ ) -> Optional[Any]: ...
201
from __future__ import annotations def lowerCAmelCase_ ( __UpperCAmelCase: list[int] , __UpperCAmelCase: int ) -> list[int]: UpperCamelCase__ : Optional[int] = 0 UpperCamelCase__ : Tuple = len(__UpperCAmelCase ) - 1...
201
1
"""simple docstring""" import os import sys import unittest __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ...
366
"""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 # ...
233
0
"""simple docstring""" def __a ( __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : str = "" for word_or_phrase in separated: if not isinstance(__lowerCamelCase, __lowerCamelCase ): raise Exception("join() accepts only strings to be joined" ) joined += ...
61
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput _SCREAMING_SNAKE_CASE : List[str] = logging.getLogger(__name__) if is_t...
127
0
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @datac...
340
"""simple docstring""" _lowerCAmelCase : dict[tuple[int, int, int], int] = {} def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> int: '''simple docstring''' if late == 3 or absent == 2: return 0 # if we have no days lef...
340
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ """camembert-base""": """https://huggingface.co/camembert...
287
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration _lowerCamelCase =5_0_0_0_0_0 _lowerCamelCase , _lowerCamelCase =os.path.split(__file__) _lowerCamelCase =os.path.join(RESULTS_BASEPATH, """results""", RESULTS_...
287
1
import unittest from knapsack import greedy_knapsack as kp class a ( unittest.TestCase ): def __UpperCAmelCase ( self ) -> Dict: _a = [10, 20, 30, 40, 50, 60] _a = [2, 4, 6, 8, 10, 12] _a = 1_00 self.as...
362
'''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_QUE...
104
0
import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" # Initialise PyTorc...
303
from heapq import heappop, heappush import numpy as np def a__ ( snake_case , snake_case , snake_case , snake_case , ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = grid.shape __SCREAMING_SNAKE_CASE : Tuple = ...
303
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVe...
3
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) fr...
3
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_to...
34
'''simple docstring''' import os from distutils.util import strtobool def snake_case_ (_a : Union[str, Any] , _a : List[Any] ): for e in env_keys: UpperCAmelCase = int(os.environ.get(_a , -1 ) ) if val >= 0: return ...
34
1
'''simple docstring''' __snake_case : Union[str, Any] = {str(digit): digit**5 for digit in range(10)} def _UpperCAmelCase ( _UpperCamelCase : int ) -> int: return sum(DIGITS_FIFTH_POWER[digit] for digit in str(_UpperCamelCase ) ) def _...
18
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case : int = logging.get_logger(__name__) __snake_case : str = { 'microsoft/xprophetnet-large-wiki100-cased': ( ...
18
1
UpperCamelCase_ = '''0.18.2''' from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available...
345
import collections import inspect import unittest from transformers import SwinvaConfig 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 ConfigTe...
345
1
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTes...
23
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = (PNDMScheduler,) SCREAMING_SNAKE_CASE__ : str ...
23
1
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging...
102
'''simple docstring''' from __future__ import annotations __lowerCAmelCase = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] __lowerCAmelCase = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def UpperCAmelCase_ (__a : list[float] ): ...
271
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepar...
366
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _lowercase = 10 def A (__lowerCamelCase :int , __lowerCamelCase :int , __lowerCamelCase...
229
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _UpperCAmelCase : int = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "...
236
import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTest...
236
1
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def lowerCamelCase (a_ :list[list[float]]) -> list[list[float]]: lowercase :Tuple = Decimal # Check if the provided matrix has 2 rows and 2 columns ...
172
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = '''\ @misc{chen2021evaluating, title={Evalu...
172
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCAmelCase : str = logging.get_logger(__name__) _UpperCAmelCase : List[Any] ...
285
import os import numpy import onnx def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' snake_case_ = a.name snake_case_ = b.name snake_case_ = '' snake_case_ = '' snake...
285
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_l...
364
def snake_case (__lowercase , __lowercase ) -> str: '''simple docstring''' _snake_case : Tuple = "" for word_or_phrase in separated: if not isinstance(__lowercase , __lowercase ): raise Exception("join() accepts only strings to ...
284
0
"""simple docstring""" def _snake_case ( lowercase__ : int ) -> Dict: '''simple docstring''' if collection == []: return [] # get some information about the collection lowerCAmelCase_ :List[Any] = len(lowercase__ ) lowerCAmelCase_ ...
84
"""simple docstring""" import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def _snake_case ( lowercase__ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ :List[Any] = ...
84
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor __snake_case : Optional[int] = logging.get_logger(__name__) class lowerCamelCase ( lowercase_ ): '''simple docstring''' def...
136
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( 'The con...
136
1
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mode...
238
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import r...
270
0
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) lowerCAmelCase__ :str = str(bin(_SCRE...
254
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def ...
254
1
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _SCREAMING_SNAKE_CASE ( __snake_case : Dict , __snake_case : int , __snake_case : Optional[int] , __snake_case : List[str] , ): ...
220
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) ...
318
0
"""simple docstring""" import os import sys import unittest lowercase__ : Any = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, creat...
368
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> list[int]: a = 2 a = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(__UpperCamelCase) if n...
180
0
from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline __snake_case = logging.get_logger(__name__) class lowercase__ ( _UpperCA...
176
def _lowercase ( UpperCamelCase_ , UpperCamelCase_ ) -> str: '''simple docstring''' if not isinstance(UpperCamelCase_ , UpperCamelCase_ ): raise ValueError('iterations must be defined as integers' ) if not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or not number >=...
176
1
__UpperCAmelCase : Optional[Any] = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import s...
293
import math def A__ ( SCREAMING_SNAKE_CASE__) -> int: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__): __snake_case: Optional[int] = F'''Input value of [number={number}] must be an integer''' raise TypeError(SCREAMING_SNAKE_CASE__) if num...
293
1
'''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 __SCREAMING_SNAKE_CASE :Dict = '''src/transfo...
22
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range...
22
1
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> bool: if not all(x.isalpha() for x in string ): raise ValueError("""String must only contain alphabetic characters.""" ) snake_case : Optional[int] = sorted(string.lower() ) return len(__lowerCamelCase ) =...
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
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeat...
187
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Optional[Any] = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], ...
106
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : List[str] = logging.get_logger(__name__) snake_case : Any = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class _snake...
281
def __lowerCamelCase ( UpperCAmelCase_ : int ): """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise TypeError('''Input value must be an \'int\' type''' ) a :Optional[int] = 0 while number: ...
281
1
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def a( A : Optional[int] ) -> List[Any]: # picklable for multi...
227
"""simple docstring""" import math class a : """simple docstring""" def __init__( self: List[Any] , UpperCamelCase: List[str]=0 ): # a graph with Node 0,1,...,N-1 """simple docstring""" A__ = n A__...
335
0
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black __lowercase : List[Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa...
294
'''simple docstring''' import re from filelock import FileLock try: import nltk __lowercase : Optional[Any] = True except (ImportError, ModuleNotFoundError): __lowercase : Dict = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) ...
294
1
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging _A = logging.get_logger(__name__) class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : Any = None @experimental d...
62
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ = { 'configuration_xlm_roberta_xl': [ 'XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaXLCo...
321
0
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 class lowercase ( snake_case__...
277
import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, Par...
277
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a__ : int = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP...
54
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER a...
54
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
364
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE :int = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_avai...
124
0
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def _A ( lowercase , lowercase=7 ): """simple docstring""" a =None if token is not None: a =...
81
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str] ): '''simple docstring''' ...
64
0
"""simple docstring""" from collections.abc import Sequence def _snake_case ( lowerCamelCase__ : Sequence[float] , lowerCamelCase__ : float ) -> float: return sum(c * (x**i) for i, c in enumerate(lowerCamelCase__ ) ) def _snake_case ( lowerCamelCase__...
209
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule A__ : Tuple = {'tokenization_byt5': ['ByT5Tokenizer']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys A__ : Dict = _LazyModule(__name__, globals()['__fi...
209
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _UpperCAmelCase : List[Any] ={ """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRCo...
262
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optio...
262
1
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = 'T5Config' de...
221
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, ImageC...
221
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase = { '''configuration_trajectory_transformer''': [ '''TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrajectoryTransformerConfig''...
87
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenizat...
254
0
"""simple docstring""" from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def _snake_case ( _snake_case : Dict ): lowerCAmelCase : Union[str, Any] = prime_factors(lowerCAmelCase_ ) if is_square_free(lowerCAmelCase_ ):...
369
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path snake_case__ : Union[str, Any] = '''src/transformers''' # Matches is_xxx_available() snake_case__ : int = re.compile(R'''is\_([a-z_]*)_available()''') # Catc...
314
0
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_( self ) -> str: lowerCamelCase_ = 10 ...
19
'''simple docstring''' import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings __snake...
4
0
'''simple docstring''' import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig fr...
264
'''simple docstring''' import sys _lowercase : Union[str, Any] = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227...
264
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { 'configuration_blip': [ 'BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlipConfig...
205
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def a ( A__ : bool = True , *A__ : int , **A__ : Union[str, Any] ) -> List[str]: """simple docstring""" ...
205
1
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly ...
89
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, requi...
89
1
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer ...
282
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def a_ ( __lowercase : Dict ) -> List[Any]: _snake_case = args.pruning_method _snake_case = args.threshold _snake_case = args.model_name_or_...
282
1
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 from transformers import ( BitConfi...
93
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax...
93
1
import functools def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = len(A__ ) __lowerCamelCase = len(A__ ) @functools.cache def min_distance(A__ : int , A__ ...
12
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar _SCREAMING_SNAKE_CASE : Optional[Any] = TypeVar('''T''') class a ( Generic[T] ): def __init__( self : List[str] ...
183
0
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_...
362
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __lowercase : '''simple...
217
0
"""simple docstring""" import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base...
25
"""simple docstring""" from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ...
25
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json', } class __snake_c...
203
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer lowercase__ = logging.get_logger(__name__)...
203
1
"""simple docstring""" from __future__ import annotations from typing import Any class _lowerCamelCase ( lowerCamelCase__ ): pass class _lowerCamelCase : def __init__(self , __a ) -> None: UpperCamelCase = data ...
153
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def UpperCAmelCase__ ( _A : int = 3 ): '''simple docstring''' if isinstance(_A , _A ): raise TypeError('''number of qubits must be a i...
188
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __snake_case = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __sna...
78
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case = { '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDepende...
78
1
import csv import tweepy # Twitter API credentials __lowerCamelCase : Dict = '''''' __lowerCamelCase : Union[str, Any] = '''''' __lowerCamelCase : Dict = '''''' __lowerCamelCase : List[Any] = '''''' def _snake_case ( lowerCAmelCase : str ): """simple d...
18
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lice...
89
0
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# snake_case__ : Any = [ # (stable-diffusion, HF Diffusers) ('''time_embed.0.weight'''...
360
'''simple docstring''' import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common impor...
274
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __snake_case = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): ...
176
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 __snake_ca...
176
1
'''simple docstring''' def __UpperCamelCase ( UpperCAmelCase ): def merge(UpperCAmelCase , UpperCAmelCase ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ...
352
'''simple docstring''' 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(): ...
214
0