code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> None: if (direction == 1 and array[indexa] > array[indexa]) or ( d...
41
"""simple docstring""" import flax.linen as nn import jax import jax.numpy as jnp class UpperCamelCase ( nn.Module ): UpperCAmelCase : int UpperCAmelCase : jnp.dtype = jnp.floataa def _lowercase (self : Any) -> Optional[int]: ...
172
0
'''simple docstring''' def lowercase (_A , _A ): """simple docstring""" return int((input_a, input_a).count(0 ) != 0 ) def lowercase (): """simple docstring""" assert nand_ga...
25
'''simple docstring''' import argparse import os import re lowerCAmelCase : Tuple = """src/transformers""" # Pattern that looks at the indentation in a line. lowerCAmelCase : str = re.compile(r"""^(\s*)\S""") # Pattern that matches `"key":" and puts `key`...
25
1
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.uti...
43
"""simple docstring""" from math import pi, sqrt, tan def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> float: '''simple docstring''' if side_length < 0: raise ValueError("""surface_area_cube() only accepts non-negative values""" ) return 6 * side_length...
136
0
'''simple docstring''' from __future__ import annotations import math def snake_case_ (UpperCamelCase : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or n...
179
'''simple docstring''' import os import re 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 _snake_case : str = logg...
179
1
a_ = { 0: """0""", 1: """1""", 2: """2""", 3: """3""", 4: """4""", 5: """5""", 6: """6""", 7: """7""", 8: """8""", 9: """9""", 10: """a""", 11: """b""", 12: """c""", 13: """d""", 14: """e""", 15: """f""", } def a__ ( _UpperCam...
330
import logging import os import threading import time try: import warnings except ImportError: a_ = None try: import msvcrt except ImportError: a_ = None try: import fcntl except ImportError: a_ = None # Backward compatibility # ---------------------------------------...
330
1
import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class __a ( __UpperCamelCase ): def __init__( self : str , *UpperCAmelCase : str , **UpperC...
370
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'uw-madison/mra-base-512-4': 'https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json', } class __a ( __Upper...
28
0
'''simple docstring''' from __future__ import annotations def _lowerCamelCase ( lowercase : float , lowercase : float , lowercase : float , ) -> tuple[str, float]: if (stress, tangential_force, area).count(0 ) != 1: raise V...
63
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets _lowerCAmelCase = datasets.logging.get_logger(__name__) _lowerCAmelCase = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Tex...
37
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a : List[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDep...
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 __future__ import annotations from typing import Any class lowercase : def __init__( self ,A__): lowercase = num_of_nodes lowercase = [] lowercase = {} def A__ ( self ,A__ ,A__ ,A__): ...
101
import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling...
216
0
"""simple docstring""" import unittest from transformers import BigBirdConfig, 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 jax from transformers...
364
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor _lowerCamelCase : List[str] = logging.get_logger(__name__) class __snake_case (_a ): def __init__( self : Optional[Any] , *_UpperCAmelCase : str , **_UpperCAmelCase...
159
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxCon...
68
def snake_case( __magic_name__ ) -> int: '''simple docstring''' lowercase : List[Any] = abs(__magic_name__ ) lowercase : Optional[Any] = 0 while n > 0: res += n % 10 n //= 10 return res ...
308
0
'''simple docstring''' import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() A__ : Union[s...
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, to...
0
1
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. __A = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must ...
135
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common...
135
1
'''simple docstring''' def __lowerCamelCase ( __lowerCAmelCase : float , __lowerCAmelCase : list[float] ) -> float: if discount_rate < 0: raise ValueError("""Discount rate cannot be negative""" ) if not cash_flows: raise ValueError(...
3
'''simple docstring''' import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __lowerCamelCase (...
3
1
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 ConfigTeste...
147
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_st...
147
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_...
357
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def __magic_name__ ( __a : Any ): # picklable for multiprocessing ''...
178
0
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class __UpperCamelCase ( unittest.TestCase , lowerCamelCase__ ): def lowercase__ ( self ): """simple docstring""" ...
75
'''simple docstring''' from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test im...
34
0
"""simple docstring""" import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu...
291
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def __lowercase ( snake_case_ : int ) ->bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 ...
291
1
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() UpperCAmelCase__ ...
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_d...
0
1
from __future__ import annotations def UpperCamelCase ( _a , _a ) -> tuple[int, int]: '''simple docstring''' if b == 0: return (1, 0) ((lowercase_) , (lowercase_)) :Dict = extended_euclid(_a , a % b ) ...
252
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_...
252
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot ...
3
'''simple docstring''' from scipy.stats import pearsonr import datasets lowercase : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of th...
3
1
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { "configuration_trajectory_transformer": [ "TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrajectoryTransf...
361
import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, ...
348
0
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ 'encoder.version', ...
54
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer ...
143
0
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.util...
197
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ : Dict = {"""configuration_swin""": ["""SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SwinConfig""", """SwinOnnxConfig"""]} try: if not is_torch_ava...
197
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase : int = logging.get_logger(__name__) _lowerCamelCase : Opt...
167
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForC...
167
1
"""simple docstring""" import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() __lowercase = logging.get_logger(__name__) __lowercase = { "post_extr...
366
"""simple docstring""" def lowercase ( A_ , A_ )-> float: '''simple docstring''' def get_matched_characters(A_ , A_ ) -> str: a : Optional[int] = [] a : List[Any] = min(len(_stra ) , len(_st...
226
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sente...
310
import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch __a = 'sshleifer/bart-tiny-random' __a = 'pa...
30
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import DebertaVaConfig, 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, ra...
274
'''simple docstring''' import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common impor...
274
1
'''simple docstring''' import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelT...
42
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { ...
195
0
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_v...
267
from __future__ import annotations import time UpperCAmelCase = list[tuple[int, int]] UpperCAmelCase = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0...
267
1
"""simple docstring""" import numpy as np def _snake_case ( UpperCamelCase : np.array ): return 1 / (1 + np.exp(-vector )) def _snake_case ( UpperCamelCase : np.array ): return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": im...
109
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer fro...
2
0
"""simple docstring""" import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter...
350
"""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 fro...
53
0
import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def _lowerCAmelCase (_lowerCAmelCase): # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_...
128
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar UpperCAmelCase : Dict =TypeVar("""T""") class _lowercase (Generic[T] ): '''simple docstring''' def __init__( self , snake_case__ ): ...
128
1
'''simple docstring''' from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures,...
351
'''simple docstring''' import math __snake_case : List[Any] = 10 __snake_case : Dict = 7 __snake_case : str = BALLS_PER_COLOUR * NUM_COLOURS def __lowerCamelCase ( __snake_case : int = 20 ) -> str: """simple docstring""...
136
0
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch clas...
11
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: _...
270
0
"""simple docstring""" UpperCAmelCase : List[Any] = range(2, 20 + 1) UpperCAmelCase : Optional[int] = [10**k for k in range(ks[-1] + 1)] UpperCAmelCase : dict[int, dict[int, list[list[int]]]] = {} def lowerCamelCase ( _UpperCamelCase : str ,...
320
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCamelCase__ ( A ): """simple docstring""" __a = ["""image_processor""", """tokenizer"""] __a = """AutoImageP...
320
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule __a = {"tokenization_byt5": ["ByT5Tokenizer"]} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys __a = _LazyModule(__name__, globals()["__file__"], _import_s...
66
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokeniz...
2
0
'''simple docstring''' from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase__ = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifi...
364
'''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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_ou...
322
0
import numpy as np from transformers import Pipeline def lowerCamelCase_ ( UpperCamelCase__ : List[Any] ) -> Any: """simple docstring""" __lowerCamelCase = np.max(UpperCamelCase__ , axis=-1 , keepdims=UpperCamelCase_...
90
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCamelCase__ = np.linspace(start=0, stop=7_5, num=7_5, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function ...
65
0
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_dete...
355
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def lowerCAmelCase__ ( a__: Sequence[float] , a__: int , a__: int ) -> tuple[int | None, int | None, float]: '''simple docstring''' ...
185
0
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging __lowerCAmelCase : int = logging.get_logger(__name__) class __lowerCAmelCase : """simple docstring""" A__ : Optional[int] ...
156
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say th...
218
0
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets lowercase : Any = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n aut...
351
'''simple docstring''' from ...processing_utils import ProcessorMixin class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = """SpeechT5FeatureExtractor""" __lowercase = """SpeechT5Tokenizer""" def __init__( self , lowerCAmelCase_ , lowerCAmelC...
160
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, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaToke...
82
'''simple docstring''' import random def lowercase__ ( __lowercase : list , __lowercase : Optional[Any] ) -> tuple: """simple docstring""" __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = [], [], [] for element in ...
53
0
"""simple docstring""" import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_av...
272
"""simple docstring""" def snake_case__ ( __lowerCamelCase : int ): """simple docstring""" lowerCamelCase__ : List[Any] =[0] * len(__lowerCamelCase ) lowerCamelCase__ : List[Any] =[] lowerCamelCase__ : List[Any] =[1] * len(__lowerCamelCase ) ...
272
1
'''simple docstring''' import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_s...
53
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.p...
173
0
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.pa...
113
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: # A local function to see if a dot lands in the circle. def is_in_circle(lowerCamelCase__ , ...
113
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
44
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTes...
44
1
'''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...
360
'''simple docstring''' lowercase =[0, 2, 4, 6, 8] lowercase =[1, 3, 5, 7, 9] def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : list[int] , __lowerCamelCase : int ): '''simple docstring''' i...
242
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint sna...
51
import argparse from collections import defaultdict import yaml lowerCAmelCase : Dict = 'docs/source/en/_toctree.yml' def A_ ( a ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = defaultdict(a ) for doc in model_doc: ...
253
0
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class _UpperCAmelCase ( _lowerCAmelCase ): def __init__( self : Optional[Any] ): # test for the above condition self.test() def a ( self : ...
365
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import...
86
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[Any] = logging.get_logger(__name__) __A : List[str] = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microso...
260
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vi...
243
0
"""simple docstring""" import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def _snake_case ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ): ...
69
"""simple docstring""" import argparse SCREAMING_SNAKE_CASE_ : Any = 'docs/source/_static/js/custom.js' def _snake_case ( UpperCAmelCase_ : List[Any] ): with open(UpperCAmelCase_ , encoding="""utf-8""" , newline="""\n""" ) as f: ...
69
1
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def lowerCAmelCase_ ( )-> Dict: '''simple docstring''' import os as original_os from os import path as original_path from os import rename as original_rename ...
348
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def lowerCAmelCase_ ( )-> int: '''simple docstring''' UpperCAmelCase : str ={ '''repo_name''': ['''test_repo1''',...
348
1
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class _a : A = None A = False A = False A = False A = None A ...
82
from typing import TYPE_CHECKING from ....utils import _LazyModule a : Tuple = {'tokenization_tapex': ['TapexTokenizer']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys a : List[Any] = _LazyModule(__name__, globals()['_...
82
1
from __future__ import annotations from fractions import Fraction def UpperCAmelCase ( a_ , a_ ) -> bool: """simple docstring""" return ( num != den and num % 1_0 == den // 1_0 and (num // 1_0) / (den % 1_0) == num / den ) def UpperCAmelCase ( a_ ) -> l...
15
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_p...
322
0
"""simple docstring""" 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 _...
181
"""simple docstring""" import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller snake_case_ = 3 def _lowerCAmelCase ( lowercase_ ): print('Generating primitive root of p' ) while True: Up...
181
1
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowercase (lowerCAmelCase_ ): _UpperCamelCase = DistilBertTokenizer _Up...
275
'''simple docstring''' from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .....
22
0
import os import sys A__ = os.path.join(os.path.dirname(__file__), '''src''') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassificati...
44
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_...
44
1
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def a_ ( lowerCAmelCase_ : str, lowerCAmelCase_ : Any, lowerCAmelCase_ : List[str] ): __lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase_ ) __lowerCAmelCas...
284
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, re...
284
1
def snake_case_(_UpperCamelCase ) -> bool: """simple docstring""" _snake_case = set() # To detect a back edge, keep track of vertices currently in the recursion stack _snake_case = set() return any( node not in visited and depth_first_search(_UpperCamel...
278
from ..utils import DummyObject, requires_backends class lowercase_ ( metaclass=__lowercase ): UpperCamelCase_ : Optional[int] = ["speech"] def __init__( self : str , *A__ : List[str] , **A__ : Tuple ) -> Optional[Any]: requi...
278
1
'''simple docstring''' from __future__ import annotations from collections.abc import Callable _UpperCamelCase = list[list[float | int]] def lowercase_ ( lowerCAmelCase__ : Matrix , lowerCAmelCase__ : Matrix ): """simple docstring""" __Uppe...
254
'''simple docstring''' from sklearn.metrics import fa_score import datasets _UpperCamelCase = ''' 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) ''' _UpperCamelCase = ''' Args: ...
254
1
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : List[Any] = set() # edges = list of graph's edges UpperCamelCase : int = get_edges(_a ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremit...
364
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __lowerCamelCase : Dict = get_tests_dir("""fixtures/spiec...
140
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencep...
170
"""simple docstring""" import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils im...
315
0
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __UpperCAmelCase :...
367
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup __UpperCAmelCase : int = logging.get_logger(__name__) class ...
315
0
"""simple docstring""" from collections.abc import Sequence from queue import Queue class lowercase: '''simple docstring''' def __init__( self: Dict, a_: Dict, a_: Any, a_: int, a_: Optional[Any]=None, a_: int=None ): ...
64
"""simple docstring""" from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_util...
153
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A ={ '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlipConfig''', '''BlipTex...
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
import itertools import math def lowerCAmelCase_ ( snake_case_ ): 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 are not primes ...
26
A_ :Optional[int] = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingf...
71
0
"""simple docstring""" 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 _UpperCamelCas...
351
"""simple docstring""" import os import sys _UpperCamelCase : str = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, Auto...
186
0
import collections import importlib.util import os import re from pathlib import Path _UpperCAmelCase : str = "src/transformers" # Matches is_xxx_available() _UpperCAmelCase : Union[str, Any] = re.compile(r"is\_([a-z_]*)_available()") # Catches a one-line _import_struct = {xxx} _UpperCAmelCase : Tupl...
236
"""simple docstring""" import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename UpperCAmelCase__ = '...
288
0
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class _UpperCAmelCase: def __init__( self , _...
100
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a = logging.get_logger(__name__) _a = { """microsoft/biogpt""": """https://huggingface.co/microsoft/biogpt/resolve/main/config.json""", # See all BioGPT mo...
100
1
from torch import nn def A ( _UpperCAmelCase : Union[str, Any] ) -> Tuple: '''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 Valu...
339
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { """t5-small""": """https://huggingface.co/t5-small/resolve/main/config.json"...
186
0
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = {"""vocab_file""": """vocab.json"""} __lowerca...
367
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowercase = { """configuration_instructblip""": [ """INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """InstructBlipConf...
226
0
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax...
55
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any...
296
0
'''simple docstring''' import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration __SCREAMING_SNAKE_CASE :Dict = 50000 __SCREAMING_SNAKE_CASE :Any = 5000 __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Optional[int] = ...
362
'''simple docstring''' def UpperCAmelCase_ ( __lowercase : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: '''simple docstring''' _UpperCAmelCase = set() # Replace all the whitespace in our sentence _UpperCAmelCase ...
156
0
"""simple docstring""" import string from math import logaa def lowercase ( __snake_case : str , __snake_case : str ): lowercase_ : Union[str, Any] = document.translate( str.maketrans('''''' , '''''' , string.punctuation ) ).replace(...
33
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Union[str, Any] = {} try: if not is_s...
33
1
'''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 ( MaxLe...
21
'''simple docstring''' import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class __magic_name__ ( ctypes.Structure): # _fields is a specific attr expected by ctypes UpperCamelCase__ ...
21
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
192
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 .tokeniza...
192
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _A = logging.get_logger(__name__) _A = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface...
369
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _A = { """configuration_layoutlmv3""": [ """LAYOUTLMV3_P...
166
0
from sklearn.metrics import recall_score import datasets SCREAMING_SNAKE_CASE :Union[str, Any] = '\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 and...
15
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied f...
65
0
'''simple docstring''' import argparse from collections import defaultdict import yaml A__ : str ='''docs/source/en/_toctree.yml''' def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase ...
220
'''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.apach...
220
1
'''simple docstring''' from math import isclose, sqrt def snake_case_ ( _lowerCAmelCase : float , _lowerCAmelCase : float , _lowerCAmelCase : float ) -> tuple[float, float, float]: UpperCAmelCase : Optional[int] = point_y /...
23
"""simple docstring""" import unittest from transformers import AutoTokenizer, FalconConfig, 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_mod...
132
0
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase__( __A ): ...
154
"""simple docstring""" import os def UpperCAmelCase ( ): """simple docstring""" with open(os.path.dirname(UpperCamelCase__ ) + '/grid.txt' ) as f: A__ = [] # noqa: E741 for _ in range(20 ): ...
154
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case : Optional[Any] = logging.get_logger(__name__) snake_case : List[Any] =...
281
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 transformers.testing_utils impo...
281
1
'''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 _snake_case (__...
67
'''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 Ba...
67
1
import functools from typing import Any def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): if not isinstance(lowerCamelCase__ , lowerCamelCase__ ) or len(lowerCamelCase__ ) == 0: raise ValueError("the string should be not empty string" ) if n...
123
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def a ( lowerCamelCase__ ): '''simple docstring''' if not sentence: return "" A_ : Optional[int] = dict(zip(lowerCamelCase__ , lowerCamelCase__ ) ) return lower_to_upper.get(senten...
206
0
"""simple docstring""" def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError("The length of profit and weight must be same." ) ...
244
"""simple docstring""" def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError("The length of profit and weight must be same." ) ...
244
1
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, Fla...
240
import inspect import unittest from transformers import DecisionTransformerConfig, 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_mod...
110
0
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging a : List[str] = logging....
353
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass...
82
0
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_ = pd.read_csv("""sample_data.csv""", header=None) a_ = df.shape[:1][0] # If yo...
330
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 if is_torch...
330
1
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 OptionalDependencyNotAvailable: f...
315
import math def a ( SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1...
315
1
from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar _snake_case = TypeVar("T") _snake_case = TypeVar("U") class UpperCAmelCase_ ( Generic[T, U]): def __init__( self, __a, __a): '''simple docstring''' ...
36
import argparse import copy def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : int = {} with open(_lowerCamelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: ...
36
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, requi...
184
'''simple docstring''' import os def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[str] = len(grid[0] ) lowerCAmelCase__ : int = len(UpperCamelCase ) lowerCAmelCase__ : Optional[int] ...
184
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _snake_case( ) -> str: lowercase : Optional[Any] = ArgumentParser( description=( """Py...
20
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Any = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-win...
44
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']} try: if not is_vision_ava...
364
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_confi...
49
0
"""simple docstring""" from manim import * class _lowerCAmelCase ( lowercase ): """simple docstring""" def _lowercase ( self : Any ): __lowercase = Rectangle(height=0.5, width=0.5 ) __lowercase = Rectangle(height=0.25, width=0.25 ...
17
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 ...tes...
39
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) snake_case : int = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2...
109
def __lowercase ( __lowerCAmelCase : int ): if num <= 0: raise ValueError('Input must be a positive integer' ) a__ = [True] * (num + 1) a__ = 2 while p * p <= num: if primes[p]: for i i...
109
1
"""simple docstring""" import os def a__ ( SCREAMING_SNAKE_CASE : str = "matrix.txt" ): '''simple docstring''' with open(os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) ) as in_file: lowerCAmelCase : Any = i...
108
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def UpperCamelCase ( _lowerCAmelCase : Any, _lowerCAmelCase : List[str], _lowerCAmelCase : Dict ) -> str: _UpperCAmelCase...
246
0
"""simple docstring""" from __future__ import annotations def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> tuple[float, list[float]]: A__ = list(range(len(lowercase_ ) ) ) A__ = [v / w for v, w in zip(lowercase_ , l...
367
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCAmelCase_ ( A_ ): lowercase__ = ['''image_processor''', '''tokenizer'''] lowercase__ = '''AutoImageProcessor''' lowercase__ ...
230
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 if...
7
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy,...
7
1
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...
365
# 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 r...
250
0