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''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = ["""image_processor""", """tokenizer"""] __lowercase = ...
42
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_pro...
264
0
"""simple docstring""" import os import sys import unittest SCREAMING_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_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dumm...
230
"""simple docstring""" from __future__ import annotations SCREAMING_SNAKE_CASE = "#" class UpperCAmelCase_ : def __init__( self : Dict ) -> None: '''simple docstring''' A__ = {} def __magic_name__ ( self : Optional[Any] ,...
230
1
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_ ( snake_case__ , snake_case__ ): @register_to_config def __init__( ...
322
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A_ ( snake_case__ ): _lowercase : ...
322
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from acce...
358
"""simple docstring""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(...
302
0
import logging from transformers.configuration_utils import PretrainedConfig SCREAMING_SNAKE_CASE__ : List[str] = logging.getLogger(__name__) class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Optional[Any] = ...
48
import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py __UpperCAmelCase : Any = "src/diffusers" # Matches is_xxx_available() __UpperCAmelCase : List[str] ...
111
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ={ "junnyu/roform...
365
"""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 ...test_modelin...
321
0
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy ...
35
"""simple docstring""" import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCAmelCase__ : Optional[int] = [ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight...
98
0
"""simple docstring""" from __future__ import annotations lowerCamelCase_ = [True] * 100_0001 lowerCamelCase_ = 2 while i * i <= 100_0000: if seive[i]: for j in range(i * i, 100_0001, i): lowerCamelCase_ = False i += 1 def snake_case ( A__ ...
253
"""simple docstring""" from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCamelCase_ : def __init__( self : Optional[Any] , lowerCAmelCase_ : Collection[float] | None = None ) -> ...
253
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, ...
78
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch ...
15
0
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time lowerCAmelCase : List[str] = Lock() def a__ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_c...
368
"""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
0
"""simple docstring""" import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def __SCREAMING_SNAK...
106
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.models.big...
87
0
"""simple docstring""" from math import pi, sqrt, tan def _lowerCAmelCase ( UpperCamelCase_ ): if side_length < 0: raise ValueError("""surface_area_cube() only accepts non-negative values""" ) return 6 * side_length**2 def _lowerCAmelCase ( UpperCamelCase_ , UpperCa...
255
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow __magic_name__ = False class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): "...
255
1
"""simple docstring""" 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 _A : Tuple = loggi...
202
"""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...
202
1
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...to...
88
from decimal import Decimal, getcontext from math import ceil, factorial def SCREAMING_SNAKE_CASE__ ( __a ): if not isinstance(__a , __a ): raise TypeError('Undefined for non-integers' ) elif precision < 1: raise ValueError('Undefined for non-natural numbers' ) ...
88
1
"""simple docstring""" import logging from transformers import PretrainedConfig _UpperCamelCase : str = logging.getLogger(__name__) _UpperCamelCase : int = { 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/ma...
220
"""simple docstring""" 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...
220
1
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, 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...
82
def lowerCAmelCase_ (lowerCAmelCase__: int , lowerCAmelCase__: float , lowerCAmelCase__: float ): """simple docstring""" return round(float(moles / volume ) * nfactor ) def lowerCAmelCase_ (lowerCAmelCase__: f...
82
1
'''simple docstring''' # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-...
41
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""",...
302
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class a_ ( _lowerCAmelCase ): @staticmethod @abstractmethod def lowercase__ ( lowercase : ArgumentParser ): """simple docs...
147
'''simple docstring''' import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCAmelCase : Any ={ '''fac...
147
1
def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str ): def get_matched_characters(__lowerCamelCase : str , __lowerCamelCase : str ) -> str: snake_case : Tuple = [] snake_case : Union[str, ...
59
'''simple docstring''' from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(import...
321
0
import collections import importlib.util import os import re from pathlib import Path _SCREAMING_SNAKE_CASE : List[str] = """src/transformers""" # Matches is_xxx_available() _SCREAMING_SNAKE_CASE : Optional[int] = re.compile(R"is\_([a-z_]*)_available()") # Catch...
360
import re from filelock import FileLock try: import nltk _SCREAMING_SNAKE_CASE : Union[str, Any] = True except (ImportError, ModuleNotFoundError): _SCREAMING_SNAKE_CASE : Optional[Any] = False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.down...
213
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dime...
253
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import t...
253
1
'''simple docstring''' import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, L...
160
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffu...
160
1
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu __UpperCAmelCase = get_tests_...
119
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModel...
168
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available SCREAMING_SNAKE_CASE__ : Any = {"tokenization_herbert": ["HerbertTokenizer"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() e...
339
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : str = "" SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] ...
339
1
"""simple docstring""" 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 transform...
264
"""simple docstring""" def __lowercase ( _a , _a , _a=False ): if isinstance(_a , _a ) and isinstance(_a , _a ): snake_case_ : Union[str, Any] = len(set_a.intersection(_a ) ) if alternative_union: snake_case_ : Any = len(_a ) + l...
264
1
'''simple docstring''' lowerCAmelCase : Dict =frozenset( [ '''prompt''', '''height''', '''width''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', '''cross_attention_...
147
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCAmelCase : int ...
147
1
def a__ ( A_ ): '''simple docstring''' if not isinstance(A_, A_ ): raise TypeError("""only integers accepted as input""" ) else: __magic_name__ = str(abs(A_ ) ) __magic_name__ = [list(A_ ) for char in range(...
88
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDi...
88
1
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class _snake_case (__UpperCamelCase , unittes...
356
'''simple docstring''' from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder _lowerCamelCase = datasets.utils.logging.get_logger(__name__) class _snake_case (folder_based_builder.FolderBasedBui...
67
0
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, ...
82
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_availabl...
82
1
from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_p...
63
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_modeling_common i...
63
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 requi...
147
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTo...
147
1
'''simple docstring''' import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, ...
363
'''simple docstring''' from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def __magic_name__( ): __lowerCAmelCase = [randint(-1_0_0_0, 1_0_0_0) for i in range(1_0)] __lowerCAmelCase = ...
9
0
'''simple docstring''' import math def lowerCamelCase (): __a : Union[str, Any] = input('Enter message: ' ) __a : List[str] = int(input(F"""Enter key [2-{len(_SCREAMING_SNAKE_CASE ) - 1}]: """ ) ) __a : Tuple = input('Encrypti...
27
"""simple docstring""" import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) class UpperCamelCase ( lowercase_ ): def __init__( self ,*__UpperCamelCase ,**__UpperCamelCase ) -...
213
0
'''simple docstring''' def __snake_case( ) -> list[list[int]]: return [list(range(1_000 - i , -1_000 - i , -1 ) ) for i in range(1_000 )] __a = generate_large_matrix() __a = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[...
43
'''simple docstring''' import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever __a = logging.getLogger(__name__) class UpperCAmelCase_ ( _a ): """simple docstring""...
43
1
"""simple docstring""" import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_availa...
160
"""simple docstring""" import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggin...
160
1
'''simple docstring''' 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) _SCREAMING_SNAKE_CASE ...
3
'''simple docstring''' import requests from bsa import BeautifulSoup def __lowerCamelCase ( __lowerCAmelCase : str , __lowerCAmelCase : dict ) -> str: snake_case = BeautifulSoup(requests.get(__lowerCAmelCase , params=__lowerCAmelCase...
3
1
__lowerCAmelCase : Union[str, Any] ='Tobias Carryer' from time import time class _lowercase : '''simple docstring''' def __init__( self :Optional[Any] , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Any , lowerCAmelCase__ :int , lowerCAmelCase__ :L...
9
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class UpperCamelCase__ ( lowercase_ ): ...
323
0
def A__ ( __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [0 for i in range(r + 1 )] # nc0 = 1 SCREAMING_SNAKE_CASE_ = 1 for i in range(1, n + 1 ): # to compute current row from previous row. SCREAMING_SNAKE_CASE_ = min(_lowerCAmelCa...
354
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_tor...
257
0
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_mvp import MvpTokenizer...
147
from collections import namedtuple a : List[Any] = namedtuple('from_to', 'from_ to') a : Tuple = { 'cubicmeter': from_to(1, 1), 'litre': from_to(0.0_0_1, 1_000), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), 'cubicyard':...
147
1
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ): for nxt...
9
'''simple docstring''' from typing import Dict, Optional import numpy as np import datasets _UpperCAmelCase : List[str] = """ IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the gro...
9
1
from math import isclose, sqrt def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : str = point_y / 4 / point_x _A : Any = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) _A : Dict = (1 - normal_gradi...
26
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__=None , UpperCa...
67
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prep...
294
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __UpperCamelCase ( lowerCAme...
294
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ : Any = {'configuration_reformer': ['REFORMER_PRETRAIN...
63
'''simple docstring''' def _lowerCamelCase ( lowercase : int ) -> bool: _a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
63
1
"""simple docstring""" import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base impor...
350
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score f...
302
0
from __future__ import annotations def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> tuple[float, list[float]]: """simple docstring""" A__ = list(range(len(lowercase_ ) ) ) A__ = [v / w for v, w in zip(l...
14
import unittest from transformers import 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 ModelTesterMixin, ids_tensor from...
9
0
'''simple docstring''' import numpy as np lowerCamelCase_ :Union[str, Any] = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] class _lowerCAmelCase : def __init__(self ...
365
'''simple docstring''' from typing import Dict from .base import GenericTensor, Pipeline class _lowerCAmelCase ( __UpperCAmelCase ): def _a (self , lowercase=None , lowercase=None , lowercase=None , **lowercase ): if tokenize_kwargs is None: A_ ...
135
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimens...
43
import math import qiskit def lowerCamelCase ( SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 1 ): '''simple docstring''' if ( isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CAS...
43
1
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLi...
198
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, skip_mps, sl...
198
1
'''simple docstring''' 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) lowercase : int ...
3
'''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 lowercas...
3
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ = {'''configuration_reformer''': ['''REFORMER_PRETRAINED_CONFIG_...
354
'''simple docstring''' from __future__ import annotations from math import pow, sqrt def __lowercase ( __lowercase , __lowercase , __lowercase ) -> dict[str, float]: '''simple docstring''' if (resistance, reactance, impedance).count(0 ) != 1: raise V...
174
0
'''simple docstring''' import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, ...
58
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece...
257
0
"""simple docstring""" class lowerCamelCase : '''simple docstring''' def __init__(self , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = set_counts UpperCAmelCase__ : str = max(_lowerCamelCase ) ...
166
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase , _lower...
166
1
from queue import PriorityQueue from typing import Any import numpy as np def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ,...
9
import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nes...
9
1
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __magic_name__ ( A , A , A , A , ) -> list[float]: snake_case , snake_case = coefficient_matrix.shape snake_case , snake_case ...
332
'''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 __magic_name__ ( A , A , A ) -> Any: # Initialise PyTorch model snake_c...
332
1
'''simple docstring''' import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @data...
85
from cva import destroyAllWindows, imread, imshow, waitKey def A__ ( __lowerCamelCase ): # getting number of pixels in the image SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(__lowerCa...
299
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinCon...
226
"""simple docstring""" from math import ceil, sqrt def lowercase ( A_ = 1_000_000 )-> int: '''simple docstring''' a : Tuple = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a : ...
226
1
'''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 transfor...
89
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class SC...
302
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__": _lowerCamelCase : Optional[Any] = pd.read_csv('''sample_data.csv''', header=None...
355
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 ConfigTester from ...
206
0
'''simple docstring''' import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _a : def __init__( self : Any , lowercase : Any , lowercase : int , lowercase : int ): '''simple docstring''' if dst_width <...
34
"""simple docstring""" import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __A = '''\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, title = {BLEU: a Method for Au...
135
0
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _snake_case ( A = 8 ) -> str: lowerCAmelCase__ = ascii_letters + digits + punctuation return "".join(secrets.choice(a__ ) for _ ...
360
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require...
228
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging __a: List[str] = logging.get_logger(__name__) class UpperCAmelCase ( a__ ): '''simple docstring''' SCREAMING_SNAKE_CASE = "encoder-decoder" ...
198
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase ( a__ , unittest.T...
198
1
from __future__ import annotations def lowerCamelCase__ ( A__ : list[int] , A__ : list[int] , A__ : int ): '''simple docstring''' __lowerCamelCase = list(range(len(A__ ) ) ) __lowerCamelCase = [v / w for v, w in zip(A__ , ...
360
from __future__ import annotations UpperCAmelCase_ = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class lowerCamelCase__: def __init__( self: Tuple , UpperCamelCase_: dict[...
29
0
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension fr...
83
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from ...
174
0
"""simple docstring""" SCREAMING_SNAKE_CASE : dict[str, float] = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "cal...
317
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters SCREAMING_SNAKE_CASE : Any = (7_2_0, 1_2_8_0) # Height, Width SCREAMING_SNAKE_CASE : List[str] = (0.4, 0.6) # if height or width lo...
317
1
'''simple docstring''' from collections.abc import Sequence from queue import Queue class _UpperCamelCase : '''simple docstring''' def __init__( self : List[Any] , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : List[str] , _lower...
166
'''simple docstring''' import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, ...
166
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'tanreinama/GPTSAN-2.8B-spout_is_uniform': ( 'https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json...
28
import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import Co...
28
1
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowercase__ ( snake_case_ :NDArray[floataa] , snake_case_ :NDArray[floataa] , snake_case_ :list[int] , ...
332
"""simple docstring""" from typing import Dict from .base import GenericTensor, Pipeline class _UpperCAmelCase ( _lowerCAmelCase ): def a ( self : Tuple , _lowercase : Dict=None , _lowercase : str=None , _lowercase : Union[str, Any]=...
332
1
import logging import os from .state import PartialState class lowercase ( logging.LoggerAdapter ): @staticmethod def __UpperCamelCase ( A_ ) -> Optional[Any]: """simple docstring""" UpperCamelCase = PartialState() return not main_process_only or (main_process_only an...
110
from __future__ import annotations def A ( lowercase , lowercase ) -> tuple[int, int]: '''simple docstring''' if b == 0: return (1, 0) ((UpperCamelCase) , (UpperCamelCase)) = extended_euclid(lowercase , a % b ) UpperCamelCase = a // b return (y, x - k ...
110
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class A ( metaclass=__snake_case ): __magic_name__ = ['''transformers''', '''torch''', '''note_seq'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_S...
3
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A =logging.get_logger(__name__) class UpperCAmelCase__ ( __UpperCamelCase ): '''simple docstring''' ...
226
0
"""simple docstring""" def snake_case (A_ :list[int] , A_ :list[int] ): '''simple docstring''' a : Optional[int] = len(A_ ) print('The following activities are selected:' ) # The first activity is always selected a : Optional[Any] ...
186
"""simple docstring""" import argparse import collections import json import os import re import string import sys import numpy as np _UpperCamelCase : Optional[Any] = re.compile(r'\b(a|an|the)\b', re.UNICODE) _UpperCamelCase : str = None def snake_case (): ...
186
1
'''simple docstring''' from __future__ import annotations def UpperCAmelCase_ ( __lowercase : list[int] ) -> bool: '''simple docstring''' return len(set(__lowercase ) ) == len(__lowercase ) if __name__ == "__main__": import doctest doc...
22
'''simple docstring''' import unittest import numpy as np from transformers import DistilBertConfig, 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(): imp...
206
0
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class __UpperCamelCase ( __SCREAMING_SNAKE_CASE ): lowerCamelCase : List[Any] ="" lowerCamelCase ...
366
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets a : Tuple = '''\ @inproceedings{snover-etal-2006-study, title = "A Study of Translation Edit Rate with Targeted Human Annotation", author = "...
79
0
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def __A ( ) -> Any: raise RuntimeError("""CUDA out of memory.""" ) class __lowerCAmelCase (...
228
'''simple docstring''' import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessin...
344
0
'''simple docstring''' import requests from bsa import BeautifulSoup def lowercase__ ( __UpperCamelCase = "https://www.worldometers.info/coronavirus" )-> dict: UpperCamelCase = BeautifulSoup(requests.get(__UpperCamelCase ).text , """html.parser""" ) ...
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
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : tuple[int, int] ,_UpperCAmelCase : int ) -> Union[str, Any]: _a : Tuple =position _a : str =[ (y + 1, x + 2), (y ...
276
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer __UpperCAmelCase = logging.get_logger(__name__)...
29
0
"""simple docstring""" from typing import List import numpy as np def _SCREAMING_SNAKE_CASE ( _lowercase : dict ) ->int: '''simple docstring''' a : str = {key: len(_lowercase ) for key, value in gen_kwargs.items() if isinstanc...
79
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noq...
79
1
a__ = { "joule": 1.0, "kilojoule": 10_00, "megajoule": 1_00_00_00, "gigajoule": 10_00_00_00_00, "wattsecond": 1.0, "watthour": 36_00, "kilowatthour": 3_60_00_00, "newtonmeter": 1.0, "calorie_nutr": 41_86.8, "kilocalorie_nutr": 4_18_68_00.00, "electronvol...
317
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructu...
317
1
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) fr...
1
"""simple docstring""" # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextMode...
1
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _lowerCamelCase : Union[str, Any] = { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/con...
28
'''simple docstring''' def __lowerCamelCase ( A__ = 10**9 ) -> int: """simple docstring""" UpperCamelCase = 1 UpperCamelCase = 2 UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = 0 while perimeter <= max_perimeter: ...
28
1
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase_...
347
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2...
347
1
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokeni...
110
from ..utils import DummyObject, requires_backends class _a ( metaclass=UpperCamelCase__ ): _lowercase : Any = ['''torch''', '''scipy'''] def __init__( self: int , *UpperCamelCase_: Any , **UpperCamelCase_: Optional[Any] ) -> List[st...
110
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a : Optional[int] = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(...
356
'''simple docstring''' import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class a ( unittest.TestCase ): def A_ ( self : List[Any] ): snake_case_ = [ '''safety_checker/pytorch_model.bin''', ...
72
0
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=2 ): from .. import __version__ A_ : Union[str, A...
186
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dim...
186
1
from __future__ import annotations from math import gcd def _UpperCamelCase (a__ :int , a__ :int = 2 , a__ :int = 1 , a__ :int = 3 , ): """simple docstring""" if num < 2: raise ValueError("""The input value cannot be ...
368
import logging from transformers.configuration_utils import PretrainedConfig UpperCamelCase__ = logging.getLogger(__name__) class __SCREAMING_SNAKE_CASE ( _a ): snake_case : Optional[Any] = """masked_bert""" def __init__( self , __lowerCAmelCase=305...
87
0
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _lowerCamelCase : str = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , *UpperCAm...
14
'''simple docstring''' from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_te...
79
0
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class UpperCamelCase__ ( __lowercase ): _SCREAMING_SNAKE_CASE : List[str] = "MCTCTFeatureExtractor" _SCREAMING_SNAKE_CASE : int = "AutoTokenizer" def __init__(self ...
359
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase__ ={ 'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'], 'configuration_data2vec_text': [ 'DA...
90
0
"""simple docstring""" from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCamelCase__ ( _lowerCamelCase : bool = True , *_lowerCamelCase : Dict ...
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
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_vision_available(): ...
81
def snake_case ( ) -> Any: for n in range(1 , 1_000_000): yield n * (n + 1) // 2 def snake_case ( snake_case__ :Dict) -> Optional[Any]: _A = 1 _A = 2 while i * i <= n: _A ...
81
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMSch...
79
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version impo...
79
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 transfo...
203
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.util...
203
1
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing...
1
'''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_utils import s...
1
1
"""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 SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) SCRE...
317
"""simple docstring""" def __UpperCAmelCase ( snake_case_ : int = 600851475143 ) -> int: """simple docstring""" try: _lowerCAmelCase = int(snake_case_ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable ...
317
1
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) class __A (snake_case__): '''s...
347
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring'''...
347
1
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class A__ ( UpperCamelCase ): """simple docstring""" UpperCamelCase_ : Optional[int] = (Eu...
17
'''simple docstring''' import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class A__ ( pl.LightningModule ): """simple docstring""" def __init__( self : Any , ...
17
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ : str = { ...
246
"""simple docstring""" 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 i...
72
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 TFModelTester...
355
'''simple docstring''' # coding=utf-8 # Copyright 2020 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/...
243
0
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_avai...
33
import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...t...
87
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_featur...
354
"""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, Resize, ...
154
0
lowercase__ : Optional[int] = { '''Pillow''': '''Pillow<10.0.0''', '''accelerate''': '''accelerate>=0.20.3''', '''av''': '''av==9.2.0''', '''beautifulsoup4''': '''beautifulsoup4''', '''black''': '''black~=23.1''', '''codecarbon''': '''codecarbon==1.2.0''', '''cookiecutter''': ''...
338
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl ...
90
0
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.d...
320
"""simple docstring""" import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput UpperCAmelCase : Optional[Any] = 'scheduler_config.json' class lowerCamelCase__ ...
320
1