code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import math def a__ ( snake_case , snake_case ): """simple docstring""" if ( not isinstance(SCREAMING_SNAKE_CASE_ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value bet...
74
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable __snake_case = { """configuration_gpt_neox_japanese""": ["""GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXJapaneseConfig"...
451
0
def snake_case (__lowercase ) -> bool: '''simple docstring''' if p < 2: raise ValueError("p should not be less than 2!" ) elif p == 2: return True _snake_case : Tuple = 4 _snake_case : str = (1 << p) - 1 for _ in rang...
704
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.test...
580
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase_ : List[str] = {"processing_layoutxlm": ["La...
21
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 SequenceFeatureExtract...
130
0
"""simple docstring""" import os def __lowerCAmelCase ( ) -> List[Any]: """simple docstring""" with open(os.path.dirname(lowercase ) + "/grid.txt" ) as f: snake_case : Optional[Any] = [] # noqa: E741 for _ in range(20 ): l.ap...
117
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig fr...
117
1
'''simple docstring''' from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def a ( UpperCamelCase_ : str = "isbn/0140328726" ) -> dict: snake_case__ =olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes ...
538
'''simple docstring''' import os SCREAMING_SNAKE_CASE__ : Optional[Any] = {'''I''': 1, '''V''': 5, '''X''': 1_0, '''L''': 5_0, '''C''': 1_0_0, '''D''': 5_0_0, '''M''': 1_0_0_0} def a ( UpperCamelCase_ : str ) -> int: snake_case__ =0 snake_case__ =0 while ind...
538
1
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_...
715
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if ...
335
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A = log...
59
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def lowercase__( A ): # A local function to see if a dot lands in the circle. def is_in_circle(A , A ) -> bool: snake_case__ : Optional[Any] ...
170
0
"""simple docstring""" def a__ ( __lowercase ) -> list: _A = int(__lowercase ) if n_element < 1: _A = ValueError("a should be a positive number" ) raise my_error _A = [1] _A = (0, 0, 0) _A = 1 while index ...
719
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base impor...
621
0
'''simple docstring''' import re from filelock import FileLock try: import nltk UpperCAmelCase__ = True except (ImportError, ModuleNotFoundError): UpperCAmelCase__ = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=Tru...
186
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { '''roberta-base''': '''...
186
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _a : int = logging.get_logger(__name__) _a : str = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/confi...
701
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : str = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch...
84
0
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf SCR...
260
"""simple docstring""" from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline SCREAMING_SNAKE_CASE : Tuple ...
260
1
'''simple docstring''' def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> int: return int(input_a == input_a == 0 ) def a__ ( ) -> None: print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(F...
312
'''simple docstring''' from __future__ import annotations def a__ ( lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None ) -> None: if start is None: UpperCAmelCase__ : List[Any] = 0 if end is None: Up...
312
1
import heapq def a_ ( SCREAMING_SNAKE_CASE__ : dict ): '''simple docstring''' _lowerCamelCase : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a P...
464
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def snake_case_ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| I...
83
0
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCAmelCase_ = logging.getLogger(__name__) class lowerCamelCase__( __lowerCamelCase): def __init__( ...
719
from __future__ import annotations def lowerCamelCase__ ( A__ : list ): '''simple docstring''' if not nums: raise ValueError("""List is empty""" ) return sum(A__ ) / len(A__ ) if __name__ == "__main__": import doctest doctest.testm...
80
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging snake_case : str = logging.get_logger(__name__) snake_case : Dict ...
335
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: fro...
335
1
def UpperCAmelCase_ ( UpperCAmelCase__ ): if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) lowercase_ = sum(UpperCAmelCase__ ) / len(UpperCAmelCase__ ) # Calculate the average return sum(abs(x - average ) for x in nums ...
720
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_comm...
650
0
import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask...
27
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Enco...
6
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''s...
51
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get...
51
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A : int = {"""configuration_glpn""": ["""GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GLPNConfig"""]} try: if not is_vision_available(): raise OptionalDepe...
100
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case : Dict = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTCo...
335
0
'''simple docstring''' a = { "km/h": 1.0, "m/s": 3.6, "mph": 1.60_9344, "knot": 1.852, } a = { "km/h": 1.0, "m/s": 0.2_7777_7778, "mph": 0.6_2137_1192, "knot": 0.5_3995_6803, } def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCa...
13
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a = logging.get_logger(__name__) a = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class __a ( ...
13
1
import unittest from transformers import DonutProcessor __lowerCAmelCase = """naver-clova-ix/donut-base""" class lowerCamelCase_ ( unittest.TestCase ): def lowercase ( self ) -> List[Any]: """simple docstring""" _UpperCamelCase = DonutProcesso...
147
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel from diffusers.utils import floa...
147
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) lowerCAmelCase = { """configuration_trocr""": ["...
713
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __A ...
551
0
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def _lowerCAmelCase ( UpperCamelCase__: List[str] ) -> Optional[Any]: """simple docstring""" A = int(number**0.5 ) return number == sq * sq def _lowerCAmelCase ( U...
641
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = { 'configuration_mobilebert': [ 'MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileBertConf...
484
0
'''simple docstring''' UpperCAmelCase_ : Any = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' ...
540
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device f...
540
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available _lowerCamelCase = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTCo...
114
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def __UpperCAmelCase( lowercase_ ): # vision encoder if "img_encoder.pos_embed" in name: _lowerCamelCase : Tuple = name.replace(...
114
1
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntime...
548
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, ...
548
1
'''simple docstring''' import math class lowerCAmelCase_ : def __init__( self , _lowerCAmelCase=0 ) -> str: # a graph with Node 0,1,...,N-1 _lowerCAmelCase = n _lowerCAmelCase = [ [math.inf for j in range(0 , _lowerCAmelCase )] for ...
18
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase__ : Tuple = logging.get_logger(__name__) lowerCamelCase__ : Any =...
698
0
'''simple docstring''' from __future__ import annotations import queue class SCREAMING_SNAKE_CASE__ : def __init__( self : Union[str, Any] , __lowerCAmelCase : str) -> Optional[int]: lowercase_ = data lowercase_ = None lowercase_ ...
714
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResamp...
461
0
def lowerCAmelCase_ (lowercase__ : List[str] , lowercase__ : Any ) -> str: '''simple docstring''' lowerCAmelCase__ = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def lowerCA...
668
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ = 5000_0000 ): lowercase__ = set() lowercase__ = int((limit - 24) ** (1 / 2) ) lowercase__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): ...
413
0
'''simple docstring''' from __future__ import annotations from scipy.special import comb # type: ignore class a : def __init__( self , __magic_name__ ) -> Tuple: _a = list_of_points # Degree determines the flexibility of the curve...
712
'''simple docstring''' 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 fro...
532
0
'''simple docstring''' import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ...
430
'''simple docstring''' from collections import deque class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : int ): """simple ...
430
1
from typing import Dict from .base import GenericTensor, Pipeline class _UpperCamelCase (a_ ): def __UpperCAmelCase ( self , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None , **__UpperCamelCase )-> Union[str, Any]: if t...
719
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : Tuple = { '''caidas/swin2sr-classicalsr-x2-64''': ( '''https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/m...
290
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @staticmethod @abstractmethod def UpperCamelCase_ ( __lowercase : ArgumentParser ): '''simple docstring''' r...
225
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from...
225
1
'''simple docstring''' import argparse A : Dict = """docs/source/_static/js/custom.js""" def _a ( lowerCamelCase_ ): with open(lowerCamelCase_ , encoding='''utf-8''' , newline='''\n''' ) as f: snake_case : Optional[Any] =f.readlines() snake_ca...
136
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A : Optional[Any] = logging.get_logger(__name__) A : Any = { """distilbert-base-unc...
136
1
from __future__ import annotations import pandas as pd def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): A_ = [0] * no_of_processes A_ = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in rang...
141
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 __lowerCamelCase = logging.getLogger(__n...
317
0
"""simple docstring""" import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterM...
706
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.ima...
200
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Tuple = logging.get_logger(__name__) a_ : Optional[int] = { 'facebook/wav2vec2-base-960h': 'https://huggingface.co/facebook/wav2vec2-base-960h/resolve/m...
73
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __magic_name__ : Optional[int] = { """configuration_swiftformer""": [ """SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", ...
672
0
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntim...
80
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging...
80
1
from typing import TYPE_CHECKING from ....utils import _LazyModule a_ = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys a_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
339
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class...
339
1
import argparse import json 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 import Acc...
714
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. lowerCamelCase : Optional[Any] = 1_0 def lowercase__( A , A , A , A ): for i in range(A , A ): ...
303
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
557
from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, req...
557
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if not len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[...
705
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if not len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[...
252
0
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('''dataset_size''' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('''input_in_memory_max_size''' , ['''default''', 0, 100 * 2**20, 900 * 2**20] ) def lowerCamelCase_...
30
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokeniz...
485
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __snake_case = { """configuration_swiftformer""": [ """SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SwiftFormerConfig...
117
"""simple docstring""" from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse("""3.8"""): import importlib_metadata else: import importlib.metadata as importlib_metadata __snake...
117
1
'''simple docstring''' from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. UpperCamelCase__ : List[str] = 2_00 # Number of elements selected in every generation of evolution. The selection takes # place from...
578
'''simple docstring''' import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def lowerCAmelCase_ ( _lowerCamelCase: Optional[int] , _lowerCamelCase: str , _lowerCamelCase: str , _lowerCamel...
578
1
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder UpperCamelCase = "__DUMMY_TRANSFORMERS_USER__" UpperCamelCase = "Dummy User" UpperCamelCase = "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" UpperCamel...
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_...
677
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, ran...
405
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : int ) -> int: """simple docstring""" if a < 0: raise ValueError('Input value must be a positive integer' ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('Inp...
405
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', ...
716
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( lowercase: ndarray ) -> float: '''simple docstring''' return np.dot(lowercase , lowercase ) class __magic_name__ : """simple docstring...
264
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a : List[str] = {"configuration_xg...
63
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch...
55
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _A = { "configuration_longt5": ["LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongT5Config", "LongT5OnnxConfig"], } try: if not is_torch_available(): raise OptionalD...
709
from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class _lowerCAmelCase ( __a ): _lowercase ='''transfo-xl''' _lo...
279
0
import os import re import shutil import sys import tempfile import unittest import black __lowerCamelCase = 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: E402 # This is the...
204
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) lowercase_ = { 'configuration_layoutlmv2': ['LAYOUTLMV2_PRETRAIN...
552
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
199
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTeste...
199
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .toke...
479
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from d...
479
1
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch SCREAMING_...
714
from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : Dict ): return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class UpperCamelCase ( ...
138
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pip...
26
def __lowerCamelCase ( A__ : float , A__ : float , A__ : float , A__ : float , A__ : float , ) -> float: lowerCamelCase_ : List[str] = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for ...
278
0
'''simple docstring''' def lowercase_ ( lowercase__ ) ->float: if not nums: # Makes sure that the list is not empty raise ValueError('List is empty' ) _snake_case: Any = sum(lowercase__ ) / len(lowercase__ ) # Calculate the average ...
273
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A : Tuple = logging.get_logger(__name__) A : Any = { 'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json', # See all BioGPT mod...
273
1
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): impor...
303
def __a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def __a ( SC...
303
1
"""simple docstring""" import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets UpperCAmelCase__ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase__ : int = '\\n@inproceedings{ble...
545
"""simple docstring""" UpperCAmelCase__ : Dict = [ (1_0_0_0, 'M'), (9_0_0, 'CM'), (5_0_0, 'D'), (4_0_0, 'CD'), (1_0_0, 'C'), (9_0, 'XC'), (5_0, 'L'), (4_0, 'XL'), (1_0, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] d...
545
1
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=_SCREAMING_SNAKE_CASE ) class a ( _SCREAMING_SNAKE_CASE ): """simple d...
426
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path __lowercase : Dict = """src/transformers""" # Matches is_xxx_available() __lowercase : Tuple = re.compile(r"""is\_([a-z_]*)_available()""") # Catches a one-lin...
142
0
from math import isclose, sqrt def UpperCamelCase ( snake_case__ : Optional[int] ,snake_case__ : List[Any] ,snake_case__ : Tuple ): '''simple docstring''' __snake_case :Dict = point_y / 4 / point_x __snake_case ...
718
def UpperCamelCase ( snake_case__ : str ,snake_case__ : int ): '''simple docstring''' __snake_case :list[list[str]] = [[] for _ in range(snake_case__ )] __snake_case :Union[str, Any] = key - 1 if key <= 0:...
291
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_ch...
508
'''simple docstring''' import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging lowercase__ = logging.get_logger(__name__) # pylint: disable=invalid-name class Up...
508
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE__ : int =logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : in...
714
"""simple docstring""" import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import ...
558
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_dat...
360
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) SCREAMING_SNAKE_CASE: Optional[int] = 2_9_9_7_9_2_4_5_8 # Symbols SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE: ...
360
1
'''simple docstring''' import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging _lowercase = logging.get_logger(__name__) def A...
706
'''simple docstring''' from math import log from scipy.constants import Boltzmann, physical_constants _lowercase = 300 # TEMPERATURE (unit = K) def A (__lowerCamelCase :float , __lowerCamelCase :float , __lowerCamelCase :float , ): if donor_conc <= 0: raise V...
162
0
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort _lowerCAmelCase = """1""" _lowerCAmelCase = """0""" _lowerCAmelCase = """1""" _lowerCAmelCase = ort.SessionOptions() _lowerCAmelCase ...
259
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class __snake...
83
0
import math def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : int ) -> int: if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE_ : Any =f'Input value of [number={number}] must be an integer' raise TypeError(Up...
431
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multipl...
431
1
"""simple docstring""" 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.Lay...
346
"""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 __A = object() # For specifying empty leaf dict `{}` __A = object() def ...
346
1
'''simple docstring''' from __future__ import annotations from math import pow, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> dict[str, float]: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only...
384
'''simple docstring''' A_ = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} A_ = ["a", "b", "c", "d", "e"] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> List[str]: lowerCamelCase_ = start # add current to vi...
384
1
def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): if dist[i][j] != float('''inf''' )...
43
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def a ( snake_case__: Any ...
97
0
"""simple docstring""" from sklearn.metrics import recall_score import datasets lowerCAmelCase__ ="\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives ...
690
"""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....
690
1
"""simple docstring""" from math import factorial A = {str(digit): factorial(digit) for digit in range(10)} def __A ( a_ :int) -> int: if not isinstance(a_ , a_): raise TypeError('''Parameter number must be int''') if number < 0: ...
52
"""simple docstring""" import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput __lowerCAmelCase : Tuple ...
58
0
'''simple docstring''' from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowercase : ...
343
'''simple docstring''' import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class ...
343
1
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging _lowercase...
192
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 if is_torch_available(): import torch if is_vision_available...
192
1
'''simple docstring''' import argparse import datetime def lowerCAmelCase_ ( lowerCamelCase ): __magic_name__ : Dict ={ """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": "...
713
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase_ ( *lowerCamelCase , lowerCamelCase = None , lowerCamelCase=True , lowerCamelCase=2 ): from .. import __version__ __magic_name__ : Optional[...
367
0
def lowercase__( A ): return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, ...
170
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow fro...
170
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : List[Any] = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": ""...
702
import collections import importlib.util import os import re from pathlib import Path a__ : str = """src/transformers""" # Matches is_xxx_available() a__ : Any = re.compile(r"""is\_([a-z_]*)_available()""") # Catches a one-line _import_struct = {xxx} a__ : List[str] = re.co...
235
0
"""simple docstring""" import math def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 ar...
434
"""simple docstring""" from jiwer import compute_measures import datasets SCREAMING_SNAKE_CASE__ : Dict ='\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to M...
434
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCAmelCase__ = lo...
594
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class _a ( low...
594
1
'''simple docstring''' def a__ ( lowerCAmelCase__ ) -> list: if len(lowerCAmelCase__ ) <= 1: return [tuple(lowerCAmelCase__ )] UpperCAmelCase__ : int = [] def generate(lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase__ ...
75
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> np.ndarray: UpperCAmelCase__ ...
75
1
'''simple docstring''' class __magic_name__ : """simple docstring""" def __init__( self , _lowercase , _lowercase , _lowercase ) -> Union[str, Any]: lowercase_ : str = None lowercase_ : Dict = None lo...
7
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A: int = logging.get_logger(__name__) A: int = { "bigcode/gpt_bigcode-santacoder": "https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json", } cl...
7
1
import warnings from ..trainer import Trainer from ..utils import logging __a : Dict = logging.get_logger(__name__) class _UpperCamelCase ( _UpperCAmelCase ): """simple docstring""" def __init__( self , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> Optional[int]: ...
534
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, ...
534
1
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ft...
495
from abc import ABC, abstractmethod from argparse import ArgumentParser class _snake_case ( UpperCAmelCase_ ): @staticmethod @abstractmethod def lowercase__ ( SCREAMING_SNAKE_CASE_): '''simple docstring''' raise NotImplementedError() @abstractme...
495
1
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, TensorFlowBenchmar...
21
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy UpperCAmelCase_ : Dict = logging.get_logger(_...
21
1
from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __lowercase( SCREAMING_SN...
585
import copy import random from transformers import CLIPTokenizer class __lowercase( SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self : Optional[Any] , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : Optional[int] ) -> str: ...
585
1
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase__ ) class lowerCAmelCase ( lowerCamelCase__ ): ...
597
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils i...
597
1
'''simple docstring''' # 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 .scheduli...
50
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Union[str, Any] = logging.get_logger(__name__) _lowercase : List[str] = { """facebook/encodec_24khz""...
50
1
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging snake_case_ = logging.get_logger...
507
'''simple docstring''' import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def __lowercase (_SCREAMING_SNAKE_CASE :List[str] ): monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pyt...
507
1
"""simple docstring""" import pprint import requests A : Optional[int] = "https://zenquotes.io/api" def _lowerCamelCase ( ): '''simple docstring''' return requests.get(API_ENDPOINT_URL + "/today" ).json() def _lowerCamelCase ( ): '''simple docstring''' return reque...
716
"""simple docstring""" import string def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = "" for i in sequence: __lowerCAmelCase = ord(_UpperCamelCase ) if 65 <= extract <= 90: output += chr(155 - extract ) ...
282
0
from __future__ import annotations import collections import pprint from pathlib import Path def _A ( __snake_case :str ) -> str: """simple docstring""" return "".join(sorted(__snake_case ) ) def _A ( __snake_case :str ) -> list[str]...
693
from __future__ import annotations _snake_case : str = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] _snake_case : Optional[int] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def _A ( __snake_case :list[float] ) ...
693
1
"""simple docstring""" import logging from transformers import PretrainedConfig _lowerCAmelCase = logging.getLogger(__name__) _lowerCAmelCase = { 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/con...
721
"""simple docstring""" from __future__ import annotations _lowerCAmelCase = [True] * 1_00_00_01 _lowerCAmelCase = 2 while i * i <= 1_00_00_00: if seive[i]: for j in range(i * i, 1_00_00_01, i): _lowerCAmelCase = False i += 1 def UpperCamelCase ...
348
0
'''simple docstring''' from __future__ import annotations import queue class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = data SCREA...
421
'''simple docstring''' # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union snake_case_ = re.compile(R'^(?P<major>\d+)' R'\.(?P<minor>\d+)' R'\.(?P<patch>\d+)$') @total_ordering @datac...
421
1
"""simple docstring""" from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *...
494
"""simple docstring""" import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class lowerCAmelCase (...
494
1
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time UpperCamelCase__ = Lock() def lowerCAmelCase_ ( __A, __A, __A, __A, __A, __A, __A ) -> str: '''simple docstring'''...
486
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_forma...
486
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase: List[str] = logging.get_logger(__name__) _lowercase: Optional[Any] = { '''tiiuae/falcon-40b''': '''https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json''', '''tiiuae/falcon-7b''': '''https:...
225
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class lowerCamelCase__ ( UpperCAmelCase ): UpperCamelCase__ ...
225
1
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_...
85
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { '''roberta-base''': '''...
186
0
'''simple docstring''' import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging __A =logging.get_logger(__name__) def _UpperCamelCase ( UpperCamelCase__ ): UpperCAme...
113
'''simple docstring''' from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake __A =numpy.array([0, 0]) __A =numpy.array([0.5, 0.8_6_6_0_2_5_4]) __A =numpy.array([1, 0]) __A =[VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] ...
113
1
def lowerCAmelCase_ ( __A ) -> float: '''simple docstring''' return 10 - x * x def lowerCAmelCase_ ( __A, __A ) -> float: '''simple docstring''' if equation(__A ) * equation(__A ) >= 0: raise Val...
486
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, ...
486
1
"""simple docstring""" import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transfor...
19
"""simple docstring""" import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def _UpperCamelCase ( _A , _A , _A ) -> List[Any]: """simple ...
19
1
import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if ...
32
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table impo...
87
0
def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : int = len(a ) __A : int = len(a ) __A : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) __A :...
77
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): ...
77
1