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 os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transf...
71
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ :Tuple = { '''configuration_x_clip''': [ '''XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XCLIPConfig''', '''XCLIPTextConfig''', ...
71
1
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging A__ : List[str]...
209
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer A__ : Dict = logging.get_logger(__name...
209
1
'''simple docstring''' from scipy.stats import pearsonr import datasets _A : Optional[int] =''' Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculati...
41
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ......
41
1
'''simple docstring''' def UpperCamelCase_( snake_case : float ): '''simple docstring''' if edge <= 0 or not isinstance(snake_case , snake_case ): raise ValueError("Length must be a positive." ) return 3 * ((2_5 + 1_0 * (5 ** (1 / 2...
92
'''simple docstring''' import os 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 logging _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(...
92
1
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params ...
97
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : str = { '''configuration_roformer''': ['''ROFORM...
54
0
from __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 from ...test_configuration_common import ConfigT...
362
from __future__ import annotations _snake_case : Union[str, Any] = [] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): for i in range(len(__lowerCamelCase ) ): if board[row][i] == 1: ...
134
0
'''simple docstring''' class A__ : def __init__( self , UpperCamelCase__ ) -> None: '''simple docstring''' A_ = len(UpperCamelCase__ ) A_ = [0] * len_array if len_array > 0: A_ = arr...
162
from ...processing_utils import ProcessorMixin class lowerCamelCase (SCREAMING_SNAKE_CASE__ ): """simple docstring""" lowerCamelCase__ = ['''image_processor''', '''feature_extractor'''] lowerCamelCase__ = '''TvltImageProcessor''' lowerCamelCase__ = '''TvltFeatureExtractor''' ...
118
0
UpperCamelCase__ = [ [0, 1_6, 1_3, 0, 0, 0], [0, 0, 1_0, 1_2, 0, 0], [0, 4, 0, 0, 1_4, 0], [0, 0, 9, 0, 0, 2_0], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def lowerCAmelCase_ ( __A, __A, __A, __A ) -> List[Any]: ''...
366
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokenizer else: Upper...
143
0
# Imports import numpy as np class __A : '''simple docstring''' def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None ): '''simple docstring''' ...
209
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a = logging.get_logger(__name__) _a = { "camembert-base": "https://huggingface.co/camembert-base/resolve/mai...
209
1
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from ...
183
'''simple docstring''' from __future__ import annotations import collections import pprint from pathlib import Path def lowercase__ ( __UpperCamelCase )-> str: return "".join(sorted(__UpperCamelCase ) ) def lowercase__ ( __UpperCamelCase...
183
1
UpperCamelCase__ = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ UpperCamelCase__ = [{"""ty...
92
class a__ ( snake_case__ ): pass class a__ ( snake_case__ ): pass class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [ [], [], [...
92
1
"""simple docstring""" def __lowerCAmelCase ( lowercase : int ) -> int: """simple docstring""" snake_case : Dict = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __lowerCAmelCase ( lowercase : i...
351
"""simple docstring""" def __lowerCAmelCase ( lowercase : int , lowercase : int , lowercase : list[list[int]] ) -> int: """simple docstring""" def update_area_of_max_square(lowercase : int , lowercase : int ) -> int: # BASE...
112
0
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 SCREAMING_SNAKE_CASE__ ( __a ): snake_case_ : Any = [] snake_case_ : Tuple = [] snake_case_ : Tup...
327
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version __snake_case : Tuple = { '<': operator.lt, '<=': operator.le, '==': operator.eq, '!=': operator.ne, '>=': operator.ge, '>': operato...
134
0
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration UpperCAmelCase : Optional[Any] = "facebook/wmt19-en-de" UpperCAmelCase : List[Any] = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model UpperCAmelCas...
360
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Dict = { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json""",...
148
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNo...
54
import gc import math import unittest import torch from diffusers import UNetaDModel from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin ...
143
0
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' UpperCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = [] for i in range(len(SCREAMING_SNAKE_CASE__ ...
61
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool = False ): '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = F'''Expected string as input, ...
61
1
"""simple docstring""" from __future__ import annotations class a : def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ) -> List[Any]: ...
183
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from ...
183
1
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator class A_ : def __init__( self: Union[str, Any] ,__lowerCAmelCase: int ): '''simple docstring''' _lowerCamelCase : List[Any] = value _lowerCamelCase : ...
362
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modu...
340
0
'''simple docstring''' def lowerCAmelCase_ ( _lowerCamelCase: dict ): __SCREAMING_SNAKE_CASE : List[str] = set() # edges = list of graph's edges __SCREAMING_SNAKE_CASE : Union[str, Any] = get_edges(_lowerCamelCase ) # While there are still elements in...
112
'''simple docstring''' 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_pipeline...
112
1
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester...
363
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging a : str ...
82
0
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 a =logging.get_logger(__name__) @da...
73
"""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__ ( lowercase__ : int , lowercase__ : List[str] ...
148
0
'''simple docstring''' import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria...
353
'''simple docstring''' import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class a__ ( UpperCAmelCase__ ): lowerCamelCa...
237
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device _a = False class A_ (unittest.TestCase ): ...
61
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_c...
61
1
"""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_te...
358
"""simple docstring""" import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from ...
320
0
from __future__ import annotations def __lowerCamelCase ( UpperCAmelCase_ : list[int] , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : list[list[str]] , UpperCAmelCase_ : int , ): """simple docstring""" a :Optional[i...
94
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { '''configuration_convbert''': ['''CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConvBertConfig''', '''Conv...
340
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_config...
100
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a = logging.get_logger(__name__) _a = { """bert-base-uncased"...
100
1
import os import re import shutil import sys import tempfile import unittest import black _snake_case = 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 reference code that will ...
36
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A__ = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpToken...
82
0
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import Confi...
145
from __future__ import annotations def lowercase__ ( __snake_case : list[int] , __snake_case : int ): '''simple docstring''' if len(__snake_case ) == 0: return False UpperCAmelCase_ : Optional[int] = len(__snake...
145
1
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 import requir...
50
'''simple docstring''' import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) __lowerCAmelCase : List[str] ={ "sample_size": 32, "in_channels": 3, "out_channels": 3, "layers_per_block": 2, ...
237
0
'''simple docstring''' from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Dict , _UpperCamelCase : Tuple , _UpperCamelCa...
365
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowercase: int = logging.get_logger(__name__) __lo...
31
0
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset UpperCAmelCase__ = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1)...
339
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''microsoft/unispeech-large-1500h-cv''': ( '''https://huggingface.co/microsoft/unisp...
320
0
"""simple docstring""" import argparse import os import re import packaging.version __UpperCamelCase : Optional[int] = '''examples/''' __UpperCamelCase : List[Any] = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("V...
74
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : int = 0 for ch in input_str: lowerCAmelCase__ : Any = ord(A_ ) lowerCAmelCase__ : Any = pow(2 , A_ ) # If we already turned on bit for current character...
74
1
"""simple docstring""" import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from t...
100
"""simple docstring""" from math import isqrt, loga def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , UpperCamelCase_ , UpperCamel...
100
1
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_...
363
'''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, requi...
274
0
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black __a = 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 t...
145
'''simple docstring''' import math def __UpperCAmelCase ( a_: int ): return math.sqrt(a_ ) * math.sqrt(a_ ) == num def __UpperCAmelCase ( a_: int ): _UpperCAmelCase : Dict = 0 _UpperCAmelCase : List[str] = n while ...
145
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : List[str] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ...
369
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : List[str] = { "configuration_bigbird_pegasus": [ "BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP", "BigBirdPeg...
89
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BlipaProcessor, BlipI...
59
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transform...
31
0
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : Dict , lowerCamelCase : int ) -> List[Any]: __snake_...
134
# 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 applic...
134
1
"""simple docstring""" _lowercase = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' _lowercase ...
74
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import...
74
1
"""simple docstring""" import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": __A : Optional[Any] = pd.read_csv('''sample_data.csv''', hea...
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): ...
27
1
from __future__ import annotations def __lowerCAmelCase ( a__ , a__ ) -> list[list[int]]: __a = [] create_all_state(1 , a__ , a__ , [] , a__ ) return result def __lowerCAmelCase ( a__ , a__ , a__ , a__ ...
6
from sklearn.metrics import fa_score import datasets A : Any = ''' The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) ''' A : List[Any] = ''' Args: predictions (`li...
274
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.or...
359
'''simple docstring''' 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 ...
243
0
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def _lowercase ( __snake_case ,__snake_case ) -> str | Literal[False]: __lowerCAmelCase : Optional[int] = list(lowerCAmelCa...
269
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str | Literal[False]: _a : Optional[int] = list(lowerCAmelCase_ ) _a ...
89
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase : Union[str, Any] = { "configuration_blenderbot": [ ...
361
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def a ( SCREAMING_SNAKE_CASE_ : dict ): ...
315
0
'''simple docstring''' from scipy.stats import spearmanr import datasets __snake_case : List[str] = '\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no c...
134
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class lowerCamelCase ( unit...
134
1
import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def lowerCamelCase__ ( UpperCamelCa...
360
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class UpperCamelCase_ ( enum.Enum ): ...
295
0
'''simple docstring''' from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def lowerCamelCase (): __a , __a : Union[str, Any] = 9, 14 # noqa: F841 __a : Optional[Any] = [ [0, 1, 4], ...
27
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Union[str, Any] = { 'configuration_blenderbot': [ ...
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase : Dict = {'''tokenization_wav2vec2_phoneme''': ['''Wav2Vec2PhonemeCTCTokenizer''']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: imp...
368
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def A ( ) -> Any: __UpperCamelCase = { 'repo_name': ['test_repo1', 'test_repo2', 'test_repo3'], 'path': ['test_1...
263
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase = { '''configuration_upernet''': ['''UperNetConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable()...
69
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class snake_case ...
243
0
'''simple docstring''' from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[Any]: if not is_accelerate_available(): ...
129
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.util...
129
1
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_S...
10
"""simple docstring""" import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met...
315
0
'''simple docstring''' import os 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 logging A_ : Any = logging.get_logger(__name__) A_ ...
368
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : List[Any] = logging.get_logger(__name__) A_ : Union[str, Any] = ...
349
0
'''simple docstring''' from itertools import permutations def __lowerCamelCase ( __snake_case : Tuple ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False ...
134
from math import isqrt def _lowerCamelCase( lowercase__ ) -> bool: '''simple docstring''' return all(number % divisor != 0 for divisor in range(2 , isqrt(lowercase__ ) + 1 ) ) def _lowerCamelCase( lowercase__ = 1_0**6 ) -> int: '''simple docstring''' __...
295
0
"""simple docstring""" import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowercase ( lowerCAmelCase__ : ...
364
"""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 __lowerCAmel...
11
0
'''simple docstring''' 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 ....
55
"""simple docstring""" import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowerCamelCase_ (UpperCamelCase__ : Optional[Any] , Uppe...
263
0
import re def UpperCamelCase ( _A ): """simple docstring""" __magic_name__ : Union[str, Any] = re.compile( R"""^(?:0|94|\+94|0{2}94)""" R"""7(0|1|2|4|5|6|7|8)""" R"""(-| |)""" R"""\d{7}$""" ) return bool(re.search(_A, _A ) ) if...
138
def UpperCamelCase ( _A = 1, _A = 1000 ): """simple docstring""" __magic_name__ : Optional[int] = 1 __magic_name__ : Dict = 0 for divide_by_number in range(_A, digit + 1 ): __magic_name__ : ...
138
1
from torch import nn def lowerCAmelCase__ ( lowerCamelCase_ : Optional[int]): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise Val...
129
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case : Dict =logging.get_logger(__name__) __snake_case : Optional[int] ={ 'facebook/xlm-roberta-xl'...
129
1
'''simple docstring''' from __future__ import annotations import numpy as np def _UpperCAmelCase ( _UpperCamelCase : list[float] ) -> List[Any]: return np.maximum(0, __UpperCamelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0...
368
'''simple docstring''' import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # 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 six # noqa: F4...
18
0
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_...
62
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelo...
349
0
__A =''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' __A =[{'''type''': '''code''', '''content''': INSTALL_C...
364
from collections import defaultdict def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = first_str.lower().strip() lowerCamelCase_ = second_str.lower().strip() # Remove whitespace lowerCamelCase_ = first_str.replace(" " ...
47
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[Any] = logging.get_logger(__name__) __A : Any = { '''facebook/timesformer''': '''https://huggingface.co/facebook/timesformer/resolve/main/co...
33
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import Back...
11
0
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __snake_case ( __lowerCamelC...
356
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, Dist...
293
0
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated __A : Tuple = collections.namedtuple('''_Datasets''', ['''train''', '...
138
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar __A : Any = TypeVar('''T''') class __A ( Generic[T] ): def __init__( self : Dict , UpperCAmelCase_ : list[T] , UpperCAmelCase_ : Callable[[T, ...
138
1
def UpperCamelCase ( _A : int )-> int: """simple docstring""" A__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def UpperCamelCase ( _A : int = 100 )-> int: """simp...
362
from manim import * class UpperCamelCase ( _UpperCAmelCase ): def __A ( self ): A__ = Rectangle(height=0.5 , width=0.5 ) A__ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) A__ = [mem.copy() for i...
198
0
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __UpperCAmelCase = TypeVar('T') class _SCREAMING_SNAKE_CASE ( Generic[T] ): UpperCAmelCase_ :deque[T] # Cache store of keys ...
84
import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def _snake_case ( lowerCAmelCase : int , lowerCAmelCase : str , lowerCAmelCase : str , lowerCAmelCase : Path , lowe...
18
0
"""simple docstring""" import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...te...
302
"""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/l...
302
1
import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class __lowerCAmelCase ( nn.Module ): snake_case_ : str = 42 snake_case_ : Optional[int] = ...
133
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class A__ ( A__ , A__ ): @register_to_config def __init__( self ...
47
0
lowercase_ = 8.314_462 # Unit - J mol-1 K-1 def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise...
20
import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = "▁" lowercase_ = {"vocab_fi...
20
1
from sklearn.metrics import fa_score import datasets __UpperCamelCase : List[str] = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" __UpperCamelCase : ...
228
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_...
293
0
from typing import Dict from .base import GenericTensor, Pipeline class __a ( __UpperCamelCase ): def A ( self : str , UpperCAmelCase : str=None , UpperCAmelCase : Union[str, Any]=None , UpperCAmelCase : str=None , **UpperCAmelCase : ...
354
from __future__ import annotations from typing import Any class __a : def __init__( self : Dict , UpperCAmelCase : int = 6 ): lowerCAmelCase_ : Node | None = None lowerCAmelCase_ : Node | None = None self....
28
0
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig 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...
146
'''simple docstring''' import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class UpperCAmelCase ( pl.LightningModule ): '''simple docstring''' def __init__( self , __lowe...
198
0
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __UpperCamelCase : List[str] = "__DUMMY_TRANSFORMERS_USER__" __UpperCamelCase : Optional[int] = "Dummy User" __UpperCamelCase : ...
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_blenderbot": [ ...
347
1
import math import sys import cva import numpy as np def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : np.ndarray , _SCREAMING_SNAKE_CASE : float ): """simple docstring""" __a = math.sqrt(_SCREAMING_SNAKE_CASE ) __a = 1 / (sigma * math.sqrt(2 * math....
302
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/r...
302
1
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing...
78
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case = { '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDepende...
78
1
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : List[Any] = { """facebook/encodec_24khz""": """https://huggin...
20
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes fro...
20
1
"""simple docstring""" import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import...
357
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) __snake_case = models.Sequential() # Step 1 - Convolutio...
169
0
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.m...
26
'''simple docstring''' import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_commo...
28
0
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) def UpperCA...
8
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs i...
8
1
"""simple docstring""" import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __SCREAMING_SNAKE_CASE : List[str] = '__DUMMY_TRANSFORMERS_USER__' __SCREAMING_SNAKE_CASE : Dict = 'Dummy...
347
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from ...
347
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_ = logging.get_logger(__name__) UpperCAmelCase_ = '▁' ...
61
'''simple docstring''' import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ ...
61
1
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.p...
78
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resi...
78
1
from __future__ import annotations def _a ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" return [ord(SCREAMING_SNAKE_CASE ) - 96 for elem in plain] def _a ( SCREAMING_SNAKE_CASE : list[int] ): """simple docstring""" return "".join(chr(el...
51
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging __UpperCamelCase : List[Any] = logging.get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE : Union[tf.Tensor, np.ndarray] ): """simple docstring""" if isinst...
51
1
def lowerCamelCase__ ( __lowerCamelCase : int ): if num < 0: return False __UpperCAmelCase : Optional[int] = num __UpperCAmelCase : Union[str, Any] = 0 while num > 0: __UpperCAmelCase : Optional[int] ...
114
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import Stable...
169
0
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, l...
362
import qiskit def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 2) -> qiskit.result.counts.Counts: '''simple docstring''' __UpperCamelCase : List[str] = qubits # Using Aer's simulator __UpperCamelCase : i...
151
0
import json import os import torch from diffusers import UNetaDModel os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True) def __SCREAMING_SNAKE...
8
from collections import deque from .hash_table import HashTable class snake_case_ ( __A ): '''simple docstring''' def __init__( self : int , *_UpperCamelCase : int , **_UpperCamelCase : Tuple ) ->Tuple: super().__init__(...
8
1
'''simple docstring''' import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('>=', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp ...
311
'''simple docstring''' import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...t...
311
1
"""simple docstring""" def __a ( __lowerCamelCase, __lowerCamelCase ): return price * (1 + tax_rate) if __name__ == "__main__": print(f"""{price_plus_tax(100, 0.25) = }""") print(f"""{price_plus_tax(125.50, 0.05) = }""")
61
"""simple docstring""" from __future__ import annotations def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance...
61
1
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __UpperCamelCase ...
350
"""simple docstring""" from __future__ import annotations def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : str , _UpperCAmelCase : list[str] | None = None ): lowerCAmelCase = word_bank or [] # create a table lowerCAmelCase = len(_UpperCAmelCase ) + 1 lowerCAmelCase ...
309
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipe...
51
def A (__A : list , __A : int , __A : int = 0 , __A : int = 0 ) -> int: """simple docstring""" UpperCAmelCase_ = right or len(__A ) - 1 if left > right: return -1 elif list_data[le...
51
1
"""simple docstring""" from scipy.stats import pearsonr import datasets __A = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumpti...
341
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise Opti...
341
1
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCas...
63
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_mul...
151
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCAmelCase = { '''configuration_resnet''': ['''RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ResNetConfig''', '''R...
42
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class lowerCamelCase__ ( _a , _a ): @register_to_config def __init__( self : str , _a : ...
42
1
'''simple docstring''' import re def lowercase ( __magic_name__ ): '''simple docstring''' return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )] def lowercase ( __magic_name__ ): '''simple docstring''' ...
311
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def lowercase ( __magic_name__ ): '''simple docstring''' for param in module.parameters(): UpperCAmelCase : Any = False def lowercase ...
311
1
"""simple docstring""" def a__ ( snake_case__ ) -> Dict: # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection lowerCamelCase = len(snake_case__ ) lowerCamelCase = max(snake_case__ ) ...
168
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMSchedu...
168
1
'''simple docstring''' from collections.abc import Callable import numpy as np def _UpperCAmelCase ( _lowerCamelCase : Callable , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ) -> np.ndarray: ...
309
'''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""", """FocalNetConfig"""]} try: ...
309
1
# Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
165
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDCondi...
165
1
'''simple docstring''' from scipy.stats import pearsonr import datasets __lowerCAmelCase = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on...
341
'''simple docstring''' import os from typing import Dict, List, Tuple, TypeVar, Union __lowerCAmelCase = TypeVar('T') __lowerCAmelCase = Union[List[T], Tuple[T, ...]] __lowerCAmelCase = Union[T, List[T], Dict[str, T]] __lowerCAmelCase = Union[str, ...
341
1
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 snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file"""...
359
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
319
0
'''simple docstring''' import warnings from ..trainer import Trainer from ..utils import logging lowercase : Optional[Any] = logging.get_logger(__name__) class __UpperCAmelCase ( _lowerCamelCase ): def __init__( self , lowerCAmelCase_=None , **...
42
'''simple docstring''' from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowercase : str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowercase : list[int] = [ord(letter)...
42
1
"""simple docstring""" from collections.abc import Sequence def A_ ( _lowerCAmelCase : Sequence[int] | None = None ): """simple docstring""" if nums is None or not nums: raise ValueError('''Input sequence should not be empty''' ) _a = nums[0] ...
153
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def A_ ( _lowerCAmelCase : Dict, _lowerCAmelCase : List[str], _lowerCAm...
153
1