code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available f...
201
def lowerCAmelCase_ ( __UpperCAmelCase: float , __UpperCAmelCase: int ) -> float: if digit_amount > 0: return round(number - int(__UpperCAmelCase ) , __UpperCAmelCase ) return number - int(__UpperCAmelCase ) if __name__ == "__main__": print...
201
1
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _lowerCamelCase(__UpperCamelCase , __UpperCamelCase , __Uppe...
341
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCamelCase__ ( __magic_name__ ): '''simple docstring''' lowerCamelCase = ['''image_processor''', '''tokenizer'''] l...
341
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE :Union[str, Any] = { 'configuration_layoutlmv3': [ 'LAYOU...
15
'''simple docstring''' import random def lowercase__ ( __lowercase : list , __lowercase : Optional[Any] ) -> tuple: """simple docstring""" __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = [], [], [] for element in ...
53
0
"""simple docstring""" from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> bool: return len(set(__SCREAMING_SNAKE_CASE ) ) == len(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
369
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import Config...
2
0
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__)...
68
import string def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): A__ = "" for symbol in message: if symbol in string.ascii_uppercase: ...
68
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Any = logging.get_logger(__name__) class __UpperCamelCase ( lowerCamelCase__ ): lowercase : Dict ='encoder-decoder' lowercase : i...
360
'''simple docstring''' import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() a_ : Any = logging.get_logger(__name__) a_ : Option...
6
0
import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils ...
7
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline lowercase : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( __UpperCAmel...
99
0
"""simple docstring""" UpperCAmelCase_ : Optional[Any] = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transfo...
361
from string import ascii_uppercase UpperCAmelCase_ : Dict = {char: i for i, char in enumerate(ascii_uppercase)} UpperCAmelCase_ : Optional[int] = dict(enumerate(ascii_uppercase)) def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str ) -> str: ...
120
0
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : Union[str, Any] = len(A_ ) for i in range(length - 1 ): lowerCAmelCase__ : Tuple = i for k in range(i + 1 , A_ ): if collection[k] < collection[least]: lowerCAmelCase__ : Optional[i...
106
'''simple docstring''' import unittest from transformers import DonutProcessor lowerCamelCase : Tuple = 'naver-clova-ix/donut-base' class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : int ): '...
2
0
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 UpperCAmelCase__ : List[str] = 'src/transformers' UpperCAmelCase__ : ...
301
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 TokenizerTesterMixin @require_tokeni...
301
1
"""simple docstring""" from collections import deque class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a ): __a = process_name # process name __a = arrival_time # arrival time of the proces...
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_nu...
45
1
'''simple docstring''' import os def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict =os.path.dirname(os.path.realpath(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ : List[str] =os.path....
350
'''simple docstring''' from decimal import Decimal, getcontext from math import ceil, factorial def _a( UpperCamelCase__ : int ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ): raise TypeError(...
222
0
"""simple docstring""" from collections import defaultdict def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): __lowercase : str = first_str.lower().strip() __lowercase : List[str] = second_str.lower().strip(...
249
'''simple docstring''' from collections.abc import Sequence def __UpperCamelCase ( lowercase__ : Sequence[float], lowercase__ : float ): '''simple docstring''' return sum(c * (x**i) for i, c in enumerate(lowercase__ ) ) def __UpperCamelCase ( lowe...
141
0
"""simple docstring""" import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FI...
255
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version __magic_name__ = { "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt, } de...
255
1
'''simple docstring''' import math def lowerCamelCase ( UpperCAmelCase__ : int = 100 ) -> int: lowercase_ : Any = sum(i * i for i in range(1 , n + 1 ) ) lowercase_ : str = int(math.pow(sum(range(1 , n + 1 ) ...
239
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentP...
239
1
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentTex...
360
'''simple docstring''' from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, D...
55
0
import math import qiskit def UpperCAmelCase_ ( __UpperCAmelCase : int = 1 , __UpperCAmelCase : int = 1 , __UpperCAmelCase : int = 1 ) -> qiskit.result.counts.Counts: if ( isinstance(__UpperCAmelCase , __UpperCAmelCase ) or isin...
225
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor lowerCamelCase__ : List[str] = logging.get_logger(__name__) class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( sel...
225
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class ...
334
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> Tuple: A: Tuple = len(__lowercase ) for i in range(length - 1 ): A: Dict = i for k in range(i + 1 , __lowercase ): ...
334
1
"""simple docstring""" def a_ ( _lowerCAmelCase : int ): '''simple docstring''' lowercase__ : list[list[int]] = [[0 for _ in range(_lowerCAmelCase )] for _ in range(m + 1 )] for i in range(m + 1 ): lowercase__ : List[Any] = 1 ...
77
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Any class UpperCamelCase : def __init__( self, lowerCAmelCase__) -> Optional[int]: snake_case_ = data snake_case_ ...
69
0
"""simple docstring""" def __snake_case ( SCREAMING_SNAKE_CASE__ : Any ) -> Tuple: '''simple docstring''' _UpperCAmelCase : Dict = len(SCREAMING_SNAKE_CASE__ ) while cur > 1: # Find the maximum number in arr _UpperCAm...
202
"""simple docstring""" import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCAmelCase : Optional[int] = logging.get_logger(__name__...
202
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase : Dict = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTCon...
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : Dict = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # S...
2
1
"""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 UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__...
318
"""simple docstring""" from itertools import permutations def _A (__a ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False SCREAMING_SNAK...
318
1
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging _UpperCAmelCase : Dict = logging.get_logger(__name__) class lowerCAmelCase : UpperCAmelCase__ = None @experimental def SCREAMING_SNAKE_...
50
import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class lowerCAmelCase ( __UpperCamelCase ): UpperCAmelCase__ = """M-CLIP""" def __init__( self : Optional[Any] , UpperCAmelCase : Union[str, Any]=1024 , UpperCAmelCas...
50
1
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __magic_name__ = logging.get_logger(__name__) def UpperCamelCase ( _A ): """simple docstring""" ...
361
import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class snake_case__ ( tf.keras.layers.Layer ): def __init__( self , lo...
138
0
import numpy as np def UpperCAmelCase__ ( _A : np.ndarray ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def UpperCAmelCase__ ( _A : np.ndarray ): '''simple docstring''' return vector * sigmoid(_A ) if __name__ ==...
188
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch f...
188
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE ={"configuration_mra": ["MRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MraConfig"]} t...
351
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlow...
321
0
import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) __snake_case :Optional[Any] = logging.getLogger() def __snake_case ( _...
49
"""simple docstring""" from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np ...
221
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class __UpperCAmelCase : __lowercase = field( metadat...
367
'''simple docstring''' import torch from transformers import AutoModel class __UpperCAmelCase ( torch.nn.Module ): def __init__( self , lowerCAmelCase_="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(lowerCAmelCase_ , self )....
160
0
import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig __A = { "facebook/maskformer-swin-base-ade": ( "https://huggingface...
10
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes...
15
0
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #...
294
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-l...
294
1
'''simple docstring''' class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Dict ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =...
152
def lowerCAmelCase__( lowercase : list[int] , lowercase : int ) -> bool: __snake_case : List[str] = len(lowercase ) __snake_case : int = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed ...
326
0
"""simple docstring""" 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 TFModelTesterMix...
298
"""simple docstring""" from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : Dict = logging.get_logger(__name__) _lowerCAmelCase : Union[str, Any] = { """snap-research/efficientformer-l1-300""": ( ...
298
1
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class a__ : A = 42 A = None # Automatically constructed ...
18
'''simple docstring''' import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=loggi...
311
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __snake_case : Any = { 'configuration_chinese_clip': [ 'CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ChineseCLIP...
18
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test...
18
1
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ...
322
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 s...
322
1
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__ :str , a__ :Union[str, Any] , a__ :Optional[int]=1024 , a__ :List[str]=1024 ...
87
def _UpperCamelCase (a__ :dict ): """simple docstring""" UpperCamelCase__ = set() # To detect a back edge, keep track of vertices currently in the recursion stack UpperCamelCase__ = set() return any( node not in v...
87
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Tuple = logging.get_logger(__name__) snake_case : Dict = { '''huggingface/informer-tourism-monthly''': ( '''https://hu...
240
def __lowercase ( __lowerCAmelCase : int , __lowerCAmelCase : float , __lowerCAmelCase : float ): return round(float(moles / volume ) * nfactor ) def __lowercase ( __lowerCAmelCase : float , __lowerCAmelCase : floa...
240
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __lowercase : List[Any] = { 'configuration_perceiver': ['PERCEIVER_PRETRAINED_CONF...
294
'''simple docstring''' import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/p022_names.txt' ) as file: __a : List[Any] = str(file.readlines()[0] ) __a : str = names.replace('"' , '' ).split('...
294
1
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ ...
313
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class a_ : """simple d...
313
1
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( A__ ) -> float: """simple docstring""" if not nums: raise ValueError('List is empty' ) return sum(A__ ) / len(A__ ) if __name__ == "__main__": imp...
350
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Union[str, Any] = { "c...
249
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ : int =logging.get_logger(__name__) lowerCAmelCase__ : Dict ={ 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class Upper...
257
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 rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILIm...
333
0
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Da...
60
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
60
1
"""simple docstring""" import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def _SCREAMING_SNAKE_CASE ( lowercase...
247
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json', # See all BioGPT models a...
180
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_pipeline_test, ...
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
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 = { '''roberta-base''': '''https://huggingface...
188
'''simple docstring''' import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( '''The `inpainting.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionInpaintPipeline` instead.''' )
112
0
import math class a_ : def __init__( self :Dict , _lowercase :Union[str, Any]=0) -> Union[str, Any]: # a graph with Node 0,1,...,N-1 UpperCAmelCase_ = n UpperCAmelCase_ = [ [math.inf for j in range(0 ...
354
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def A ( __UpperCAmelCase ) -> Dict[str, torch.Tensor]: '''simple docstring''' UpperCAmelCase_ = [] UpperC...
344
0
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .t...
38
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging __A : Tuple = logging.get_logger(__name__) __A : List[Any] = R''' Args: input_ids (`torch.LongTensor` o...
138
0
'''simple docstring''' from collections.abc import Sequence def UpperCamelCase( UpperCAmelCase_ = None ): if nums is None or not nums: raise ValueError('Input sequence should not be empty' ) UpperCAmelCase : str = nums[0] for i in range(1 , len(UpperCAmelCase_ ...
280
'''simple docstring''' # Lint as: python3 import itertools import os import re lowercase__ = re.compile(r"([A-Z]+)([A-Z][a-z])") lowercase__ = re.compile(r"([a-z\d])([A-Z])") lowercase__ = re.compile(r"(?<!_)_(?!_)") lowercase__ = re.compile(r"(_{2...
280
1
'''simple docstring''' from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTrans...
319
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase = {'''configuration_focalnet''': ['''FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FocalNetCon...
319
1
'''simple docstring''' def a__ ( lowercase : int ) -> Tuple: """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 _UpperCamelCase = 1 _UpperCamelCase = 1 while repunit: _UpperCamelCase = (10 * repunit + 1) % ...
361
'''simple docstring''' from math import isclose, sqrt def a__ ( lowercase : float, lowercase : float, lowercase : float ) -> tuple[float, float, float]: """simple docstring""" _UpperCamelCase = point_y / 4 / point_x _UpperCamelCase = 2 * normal_grad...
287
0
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _a ( __a ): def __init__( self : str , lowercase ...
34
'''simple docstring''' from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _conc...
34
1
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
355
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __lowercase : str = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 E...
294
0
"""simple docstring""" from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowercase : Optional[int] = logging.get_logger(__name__) _lowercase : List[Any] = { 'nielsr/canine-s': ...
332
"""simple docstring""" from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor ...
332
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate impor...
352
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention...
208
0
'''simple docstring''' from collections import deque def snake_case_ ( lowerCAmelCase_ )-> Dict: '''simple docstring''' _UpperCAmelCase : Optional[int] = len(lowerCAmelCase_ ) _UpperCAmelCase : Optional[int] = deque() _UpperCAmelC...
215
'''simple docstring''' import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )-...
215
1
from sklearn.metrics import mean_squared_error import datasets __A : Union[str, Any] ='''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhof...
350
import copy import re class _SCREAMING_SNAKE_CASE : lowerCAmelCase__ = 'hp' lowerCAmelCase__ = {} lowerCAmelCase__ = None @classmethod def SCREAMING_SNAKE_CASE_( cls , lowercase , lowercase ) -> Tuple: lowerCamelCase_ = prefix ...
47
0
def _a ( UpperCamelCase_ : int , UpperCamelCase_ : int ) -> str: """simple docstring""" return "\n".join( F"{number} * {i} = {number * i}" for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplica...
340
from __future__ import annotations from cmath import sqrt def _a ( UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> tuple[complex, complex]: """simple docstring""" if a == 0: raise ValueError("Coefficient...
340
1
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] = { "t5-small": "...
339
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
339
1
def __snake_case ( __UpperCamelCase : str ): """simple docstring""" assert column_title.isupper() A_ = 0 A_ = len(__UpperCamelCase ) - 1 A_ = 0 while index >= 0: A_ = (ord(column_title[index] ...
312
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Pa...
312
1
def lowerCAmelCase_ ( __lowerCAmelCase )-> int: '''simple docstring''' UpperCAmelCase : Tuple =abs(__lowerCAmelCase ) UpperCAmelCase : List[Any] =0 while n > 0: res += n % 10 n //= 10 return res def low...
78
import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py __snake_case ...
78
1
'''simple docstring''' from typing import Dict, Optional import numpy as np import datasets snake_case_ : str = """ IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth. For bina...
125
import sys from collections import defaultdict class a__ : """simple docstring""" def __init__( self : Union[str, Any] ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = ...
245
0
'''simple docstring''' from __future__ import annotations import requests def _A ( _lowerCAmelCase ): """simple docstring""" __lowercase =f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(_lowerCAmelCase ).json() ...
369
'''simple docstring''' from __future__ import annotations import math import random from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : List[Any]): '''simple docstring''' __lowercase =[] ...
48
0
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class A__ ( A__ ): def A ( self : Optional[Any] ) -> str: '''simple docstring''' return [ {"col_1": 3...
47
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase = { '''configuration_deberta''': ['''DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DebertaConfig''...
188
0
"""simple docstring""" def _lowercase ( _UpperCAmelCase = 60_08_51_47_51_43 ) -> int: try: lowerCamelCase =int(lowerCAmelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise Val...
361
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassif...
262
0
'''simple docstring''' import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def _UpperCAmelCase ( _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCam...
309
'''simple docstring''' # Algorithm for the pigeonhole sorting def _UpperCAmelCase ( _lowerCamelCase : Union[str, Any] ) -> List[Any]: _lowerCAmelCase : List[Any] = min(_lowerCamelCase ) # min() finds the minimum value _lowerCAmelCase : Tuple = max(_lower...
309
1
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Opti...
370
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 import BertConfig from tra...
127
0
import numpy as np from transformers import Pipeline def A ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: lowerCamelCase : Dict = np.max(_SCREAMING_SNAKE_CASE ,axis=-1 ,keepdims=_SCREAMING_SNAKE_CASE ) lowerCamelCase : Dict = np.exp(outputs -...
48
"""simple docstring""" from __future__ import annotations import numpy as np def UpperCAmelCase__ ( lowerCAmelCase__ :list[float] ) -> Optional[Any]: '''simple docstring''' return np.maximum(0 , lowerCAmelCase__ ) if __name__ == "__main__": p...
197
0
import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow a__ = False class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" ...
367
import argparse import os import torch from transformers.utils import WEIGHTS_NAME a__ = ['''small''', '''medium''', '''large'''] a__ = '''lm_head.decoder.weight''' a__ = '''lm_head.weight''' def __UpperCAmelCase ( __a : str ,__a : str ) -> ...
15
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property ...
16
"""simple docstring""" import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeach...
16
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''s-JoL/Open-Llama-V1''': '''https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json''', } class __a ( ...
288
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def snake_case_ ( snake_case = 3 ) -> qiskit.result.counts.Counts: if isinstance(snake_case , snake_case ): raise...
288
1
"""simple docstring""" from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def a_ ( ): '''simple docstring''' lowercase__ : Dict = [randint(-1000 , 1000 ) for i in range(10 )] low...
77
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 fr...
159
0
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable...
367
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() pars...
129
0
"""simple docstring""" from __future__ import annotations import math def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = u for i in range(1 , __UpperCamelCase ): __A = temp * (u - i) return temp def ...
266
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("...
266
1
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, Prop...
355
from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class __lowerCamelCase ( snake_case_ ...
297
0
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 # noqa: F401 # Here...
110
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_...
284
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { "microsoft/focalnet-tiny": "https://huggingfac...
357
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
0
import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtraction...
146
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 ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : s...
146
1
'''simple docstring''' import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": UpperCamelCase__ = '''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(input...
364
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import...
299
0
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class lowerCamelCase (_snake_case ): '''simple docstring''' def __UpperCAmelCase ( self , _UpperCamelCase ) -> int: wit...
29
'''simple docstring''' import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, ...
323
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE ( metaclass=a_ ): """simple docstring""" lowercase__ = ["sentencepiece"] def __init__( self : Dict ,*lowercase_ : Tuple ,**lowercase_ ...
74
"""simple docstring""" from __future__ import annotations from math import pow, sqrt def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ ): if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance == 0: return {"r...
74
1
def A ( _SCREAMING_SNAKE_CASE = 50 ) -> int: lowerCamelCase : str = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 ,5 ): for tile_start in range(row_length - tile_length + 1 ): ...
48
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determin...
123
0
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path UpperCAmelCase_ = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa impo...
360
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ = { 'configuration...
247
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase : Optional[Any] = { 'configuration_x_clip': [ 'XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XCLIPConfig', 'XCLIPTextConfig', 'XCLIPVi...
107
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDCon...
119
0
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 __a ( __UpperCamelCase ,unittest.TestCase ): __...
28
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 @dataclass class __a ( __UpperCame...
28
1
'''simple docstring''' 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, PreTrainedTok...
211
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 1000 ) -> int: lowerCamelCase__ : str = -1 lowerCamelCase__ : Dict = 0 for a in range(1 , n // 3 ): # Solving the tw...
41
0
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class __UpperCamelCase : lowercase : int lowercase : Node | None =None ...
6
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __UpperCamelCase ( ...
6
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDCondi...
285
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowercase ( lowercase_ ): @staticmethod @abstractmethod def a ( snake_case ): raise NotImplementedError() @abstractmethod def a ( self ): ...
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_funnel import FunnelTokenizer lowerCamelCase = logging.get_logger(__name__) lowerCamelCase ...
211
import math class _a : def __init__( self : List[Any] , _SCREAMING_SNAKE_CASE : Any=0 )-> Optional[Any]: # a graph with Node 0,1,...,N-1 lowerCAmelCase__ : Optional[int] = n lowerCAmelCase__ : List[Any] = [ [math.inf fo...
211
1
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 OptionalDependencyNotAvailabl...
90
def _SCREAMING_SNAKE_CASE ( lowercase : float , lowercase : list[float] ): '''simple docstring''' if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash ...
204
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json', } class __a ( __SCR...
366
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer __UpperCAmelCase = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __UpperCAmelCase...
28
0
"""simple docstring""" import requests _A = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=""" def a__ ( lowerCAmelCase ) -> None: # fetching a list of articles in json format UpperCAmelCase__ : Any = requests.get(_NEWS_API + bbc_news_api_key...
171
"""simple docstring""" import copy import random from transformers import CLIPTokenizer class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__(self , *_lowerCamelCase , **_lowerCamelCase ): """simple docstring""" super().__init__(*_...
171
1
'''simple docstring''' import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available,...
356
'''simple docstring''' _SCREAMING_SNAKE_CASE = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C''']...
217
0
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) a__ = pytest.mark.integration @pytest.mark.parametrize('''path''' ,['''paws''', '''cs...
235
A : Union[str, Any] = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} A : List[Any] = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def UpperCamelCase ( __magic_name__ : dict[int, list[int]] , __magic_name__ : int , __magic_name__ ...
305
0
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class SCR...
190
'''simple docstring''' import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, ...
190
1
'''simple docstring''' import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asd...
168
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModel...
168
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailab...
362
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 class __a ( __UpperCa...
28
0
"""simple docstring""" import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> Tuple: def wrapper(*SCREAMING_SNAKE_CASE_ : Union...
113
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def lowercase (SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any=False ) -> str: SCREAMING_SNAKE_CASE = ...
113
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers,...
370
"""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 test...
57
0
# 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...
287
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...
287
1
from ..utils import DummyObject, requires_backends class __magic_name__ (metaclass=_a ): lowerCamelCase__ = ["""keras_nlp"""] def __init__( self , *_a , **_a ) -> Union[str, Any]: requires_backends(self , ["keras_nlp"] )
367
import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import log...
22
0