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
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType l...
178
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(): from transform...
178
1
import importlib.metadata import operator import re import sys from typing import Optional from packaging import version _UpperCAmelCase : List[Any] = { """<""": operator.lt, """<=""": operator.le, """==""": operator.eq, """!=""": operator.ne, """>=""": operator.ge, """>""":...
200
from math import sqrt def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case_ = 0 for i in range(1 , int(sqrt(UpperCamelCase__ ) + 1 ) ): if n % i == 0 and i != sqrt(UpperCamelCase__ ): ...
200
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( ...
86
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def lowerCamelCase_ ( _a : List[Any] ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = [ """decoder.version""", ...
345
0
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("""Googling.....""") UpperCamelCase__ : List[Any] = """https://www.google.com/search?q=""" + """ """.join(sys.argv[1:]) UpperCamelCase__ : L...
351
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 @r...
330
0
'''simple docstring''' import requests snake_case_ : int = '' # <-- Put your OpenWeatherMap appid here! snake_case_ : Dict = 'https://api.openweathermap.org/data/2.5/' def A__ ( UpperCAmelCase_ = "Chicago" , UpperCAmelCase_ = APPID ): return requests.get(URL_BASE + 'we...
83
'''simple docstring''' import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(lowercase )...
83
1
class UpperCAmelCase_ : """simple docstring""" def __init__( self ) -> None: _a : dict[str, TrieNode] = {} # Mapping from char to TrieNode _a : Optional[int] = False def __lowercase ( sel...
365
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a__ = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X"...
15
0
"""simple docstring""" import copy import os import cva import numpy as np from matplotlib import pyplot as plt class A_ : """simple docstring""" def __init__( self :List[Any] ): """simple docstring""" lowerCamelCase__ : ...
126
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, loggi...
126
1
import os import sys import unittest UpperCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model...
353
"""simple docstring""" from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets UpperCAmelCase = """\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex...
54
0
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBer...
296
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def __SCREAMING_SNAKE_CASE ( A_ = 1_00_00_00 , A_ = 10 ): lowerCAmelCase__ : defaultdict = defaultdict(A_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_wi...
106
0
'''simple docstring''' import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallb...
107
'''simple docstring''' from math import sqrt def __lowerCamelCase ( lowerCAmelCase_ ) -> int: _a : Dict = 0 for i in range(1 , int(sqrt(lowerCAmelCase_ ) + 1 ) ): if n % i == 0 and i != sqrt(lowerCAmelCase_ ): total += i + n // i elif i == sqr...
107
1
'''simple docstring''' from collections import defaultdict class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = total # total no of tasks (N) # DP table ...
97
'''simple docstring''' from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("""repo_id""" , ["""canonical_dataset_name""", """org-name/dataset-name"""] ) @pytest.mark.parametrize("""path""" , ["""filename.csv""", """filename with b...
239
0
'''simple docstring''' import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp ...
361
'''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/...
4
0
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowerCamelCase ( _UpperCamelCase : Optional[Any] ) -> Optional[int]: '''simple docstring''' return ConvertCommand( ...
115
"""simple docstring""" from __future__ import annotations class UpperCamelCase_ : def __init__( self : Any , lowerCAmelCase_ : int ) -> None: UpperCAmelCase_ : Any = data UpperCAmelCase_ : Node | None = None UpperCAmelCase_ ...
268
0
"""simple docstring""" import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def __lowercase ( _a , _a , _a , _a=1_024 ): snake_case_ : str = [], [] snake_case_ : Union[str, Any] = ...
356
"""simple docstring""" import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp ...
155
0
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def lowerCAmelCase__ ( lowerCamelCase_ : Any): '''simple docstring''' if "img_encoder.pos_embed" in name: lowerCAmelCase__ : Dict ...
129
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 lowerCamelCase__ ( lowerCamelCase__): '''simp...
129
1
'''simple docstring''' import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def _lowercase ( __A ): '''simple docstring''' ...
243
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _lowercase ( *__A ): '''simple docstring''' if not isinstance(__A ,__A ): __UpperCamelCase = list(_...
243
1
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( "The converted tokenizer will b...
26
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowercase( __a ): '''simple docstring''' lowercase__ = ["image_processor", "tokenizer"] lowercase__...
64
0
'''simple docstring''' import math def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Tuple = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(__SCR...
264
'''simple docstring''' import qiskit def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = qiskit.Aer.get_backend('''aer_simulator''' ) # Cre...
264
1
"""simple docstring""" def a_ ( lowerCamelCase = 6_0_0_8_5_1_4_7_5_1_4_3 ): try: UpperCAmelCase__ = int(a__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise Value...
98
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __snake_case : Dict = logging.get_logger(__name__) __snake_case : Any ...
248
0
'''simple docstring''' from __future__ import annotations import math def UpperCamelCase ( a , a ) -> list: '''simple docstring''' if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('''Matrices are not 2x2''' ) ...
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapT...
98
0
from math import pi, sqrt, tan def lowerCamelCase_ ( lowerCamelCase__ ): if side_length < 0: raise ValueError("surface_area_cube() only accepts non-negative values" ) return 6 * side_length**2 def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):...
19
"""simple docstring""" import os def lowerCamelCase__ ( ) -> List[Any]: with open(os.path.dirname(_lowerCamelCase ) + '/grid.txt' ) as f: lowerCamelCase_ = [] # noqa: E741 for _ in range(20 ): l.append([int(_lowerCamelCas...
183
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureEx...
369
"""simple docstring""" from ...processing_utils import ProcessorMixin class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "WhisperFeatureExtractor" __lowerCAmelCase = "WhisperTokenizer" def __init__( self ...
215
0
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position lowercase__ :int = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWar...
101
import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAIN...
101
1
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" if not nums: return 0 lowerCAmelCase__ : Tuple = nums[0] lowerCAmelCase__ : List[Any] = 0 for num in nums[1:]...
184
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase = 1000 ): """simple docstring""" lowerCAmelCase__ : Union[str, Any] = -1 lowerCAmelCase__ : Optional[Any] = 0 for a in range(1 , n // 3 ): # Solving the two equa...
184
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { "configuration_xlm_roberta_xl": [ "XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaXLConfig", "XLMRobertaXLOnnxConfig", ], } try: ...
10
import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase__ : Optional[Any] = logging.get_logger(__name__) lowercase__ : ...
187
0
from math import ceil, sqrt def __lowercase ( __lowerCAmelCase : int = 1_0_0_0_0_0_0 ): a__ = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a__ = max(ceil(sqrt(outer_width**2 ...
363
from math import ceil, sqrt def __lowercase ( __lowerCAmelCase : int = 1_0_0_0_0_0_0 ): a__ = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a__ = max(ceil(sqrt(outer_width**2 ...
109
0
"""simple docstring""" import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCr...
17
"""simple docstring""" import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import...
17
1
def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : int ): """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(lowerCAmelCase_ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod ...
362
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageC...
221
0
"""simple docstring""" from collections import Counter from timeit import timeit def a_ ( _lowerCAmelCase : str = "" , ): '''simple docstring''' return sum(c % 2 for c in Counter(input_str.replace(' ' , '' ).lower() ).values() ) < 2 def a_ ( ...
77
"""simple docstring""" import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=__snake_case , defaul...
220
0
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging log...
226
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..imag...
226
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 A : List[Any] = get_tests_dir() +...
118
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def a__ ( __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = k_size // 2 SCREAMING_SNAKE_CASE_ , ...
118
1
from __future__ import annotations from math import pow, sqrt def _UpperCamelCase ( snake_case__, snake_case__, snake_case__ ) -> dict[str, float]: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError("One and only one argument m...
342
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) f...
342
1
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_o...
34
def _UpperCAmelCase (UpperCamelCase__ : str , UpperCamelCase__ : bool = False ): if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): _A : Optional[Any] = f"Expected string as input, found {type(UpperCamelCase__ )}" ...
11
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX mode...
370
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import...
296
0
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable _snake_case = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try:...
283
'''simple docstring''' # using dfs for finding eulerian path traversal def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None )-> List[str]: '''simple docstring''' _UpperCAmelCase : Any = (path or...
215
0
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( lowerCamelCase_ : list , lowerCamelCase_ : int ): # Checks if the entire collection has been sorted if len(lowerCamelCase_ ) <= 1 or n <= 1: return insert_n...
360
'''simple docstring''' def _lowerCAmelCase ( lowerCamelCase_ : str , lowerCamelCase_ : str ): __lowercase = len(lowerCamelCase_ ) + 1 __lowercase = len(lowerCamelCase_ ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefi...
217
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils i...
165
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ : List[str] = {"configuration_yolos": ["YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP", "YolosConfig", "YolosOnnxConfig"]} t...
165
1
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def ...
193
class UpperCamelCase__ : '''simple docstring''' def __init__( self : int ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> ...
193
1
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: lowerCamelCase__ : List[str] = AutoConfig.from_pre...
50
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_se...
89
0
"""simple docstring""" import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib SCREAMING...
357
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-...
149
0
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClas...
337
"""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, pre...
106
0
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCamelCase__ ( __lowercase , unittest.TestCase ): """simple docstring""" ...
352
def A__ ( __lowerCamelCase = 10_00 ): return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1 ) ) if __name__ == "__main__": print(solution())
257
0
from typing import Dict from .base import GenericTensor, Pipeline class snake_case ( UpperCAmelCase__ ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[int] , lowerCAmelCase : Any=None , lowerCAmelCase : ...
317
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging ...
291
0
def _A ( lowercase , lowercase , lowercase ): """simple docstring""" return round(float(moles / volume ) * nfactor ) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" return round(float((moles * 0.0821 * temperatur...
360
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_...
215
0
from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_...
21
import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, ...
230
0
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) __A : Dict = logging.getLogger(__name__) ...
366
"""simple docstring""" import math def lowercase ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int = 0 , _SCREAMING_SNAKE_CASE : int = 0 ): '''simple docstring''' _UpperCAmelCase = end or len(_SCREAMING_SNA...
326
0
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py SCREAMING_SNAKE_CASE : int = "src/transform...
21
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( Autoe...
297
0
"""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, ...
108
"""simple docstring""" from math import ceil def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: __lowerCAmelCase: Tuple = list(range(0 , __SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase: Optional[Any] = [item for sublist in list(de...
108
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A__: List[str] = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig'...
149
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin ...
149
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor A__ : str =logging.get_logger(__name__) class UpperCAmelCase ( snake_case_ ): def __init__( self ...
220
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available A__ : int ={'''tokenization_herbert''': ['''HerbertTokenizer''']} try: if not is_tokenizers_available(): ...
220
1
from typing import Any import numpy as np def _UpperCamelCase ( lowercase__ ): return np.array_equal(lowercase__ , matrix.conjugate().T ) def _UpperCamelCase ( lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Union[st...
9
import os import jsonlines import numpy as np from tqdm import tqdm __snake_case : Any =2_0_4_8 __snake_case : Union[str, Any] =4_0_9_6 __snake_case : Optional[Any] =4_2 __snake_case : Dict =os.environ.pop('PROCESS_TRAIN', 'false') __snake_case : List[str] ...
129
0
from typing import TYPE_CHECKING from ....utils import _LazyModule lowerCAmelCase_ = {'tokenization_tapex': ['TapexTokenizer']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'...
355
import math def snake_case( __magic_name__ ) -> bool: '''simple docstring''' lowercase : Union[str, Any] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(__magic_name__ ) def sna...
116
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase ) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _UpperCAmelCase : str = ...
282
class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self : List[str] , lowercase : list[int] ): '''simple docstring''' _snake_case = len(lowercase ) _snake_case = [0] * len_array if len_array > 0: _snake_case = array[0] for i in range...
282
1
'''simple docstring''' from __future__ import annotations from math import ceil, floor, sqrt def SCREAMING_SNAKE_CASE__ ( __A = 2_000_000 ) -> int: _snake_case = [0] _snake_case = 42 for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ...
350
'''simple docstring''' import os import sys import unittest lowercase : List[str] = 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, cr...
160
0
"""simple docstring""" def __a ( __lowerCamelCase, __lowerCamelCase ): return int(input_a == input_a == 0 ) def __a ( ): print("Truth Table of NOR Gate:" ) print("| Input 1 | Input 2 | Output |" ) print(f"""| 0 | 0 | {nor_gate(0, 0 )} |""" ) p...
61
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_te...
61
1
'''simple docstring''' from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class a__ ( UpperCAmelCase__ ): lowerCamelCase : ...
237
'''simple docstring''' import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECO...
237
1
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_availabl...
345
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _snake_case ( __snake_case , unittest.TestCase ): '''simple docstring''' A...
345
1
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch _UpperCAmelCase :...
45
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, Res...
45
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 A : List[Any] = logging.get_logger(__name__) A : List[str] = { "facebook/lev...
118
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def a__ ( __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = k_size // 2 SCREAMING_SNAKE_CASE_ , ...
118
1
'''simple docstring''' import datasets lowercase : Tuple = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n ...
311
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_au...
311
1
'''simple docstring''' 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.st...
3
'''simple docstring''' import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import ...
3
1
'''simple docstring''' from __future__ import annotations import math import random from typing import Any class A_ : '''simple docstring''' def __init__( self : Tuple ) -> None: UpperCAmelCase : list[Any] = [] UpperCAmelCas...
280
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ...
280
1
"""simple docstring""" import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline __lowerCamelCase = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False) parser....
221
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_t...
221
1
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap _UpperCAmelCase = 'Usage of script: script_name <size_of_canvas:int>' _UpperCAmelCase = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def lowerCAmelCase_ ( Upper...
328
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { 'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'], 'tokenization_tapas': ['TapasTokenizer'], } try: if not i...
328
1
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, r...
82
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDI...
82
1
"""simple docstring""" from maths.prime_factors import prime_factors def __lowerCamelCase ( __UpperCamelCase ) -> int: """simple docstring""" if not isinstance(__UpperCamelCase , __UpperCamelCase ): lowerCAmelCase_ : Dict = f'''Input value of [number={numbe...
161
"""simple docstring""" import argparse import os import re lowercase__ = """src/transformers""" # Pattern that looks at the indentation in a line. lowercase__ = re.compile(r"""^(\s*)\S""") # Pattern that matches `"key":" and puts `key` in group 0. lowercase__ = re.compile(r"""^\s*\...
161
1
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info(...
107
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCAmelCase : str = logging.get_logger(__name__) __lowerCAmelCase : Dict = {...
107
1
def snake_case (__lowercase ) -> bool: '''simple docstring''' if p < 2: raise ValueError("p should not be less than 2!" ) elif p == 2: return True _snake_case : Tuple = 4 _snake_case : Dict = (1 << p) - 1 for _ ...
284
from __future__ import annotations def snake_case (__lowercase , __lowercase ) -> float: '''simple docstring''' _snake_case : Any = sorted(numsa + numsa ) _snake_case ,_snake_case : Any = divmod(len(__lowercase ) , 2 ) if mod...
284
1
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosi...
4
'''simple docstring''' a_ : str = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ a_ : Any...
55
0
"""simple docstring""" import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import ...
313
"""simple docstring""" import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import ...
313
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE_ = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], ...
296
from pathlib import Path import fire def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = ...
296
1
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, Se...
363
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) f...
235
0
import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallback, TrainingArgumen...
302
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor impor...
302
1
"""simple docstring""" from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def lowerCAmelCase__ ( _UpperCamelCase : np.ndarray , _UpperCamelCase : np.ndarray , _UpperCamelCase : np.ndarray , _UpperCamelCase : int , ...
149
"""simple docstring""" import os def lowerCAmelCase__ ( _UpperCamelCase : str = "matrix.txt" ) -> int: """simple docstring""" with open(os.path.join(os.path.dirname(_UpperCamelCase ) , _UpperCamelCase ) ) as in_file: snake_ca...
149
1
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert...
182
'''simple docstring''' class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Any = None A : Optio...
3
0
"""simple docstring""" import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration lowerCamelCase__ = 500_000 lowerCamelCase__ , lowerCamelCase__ = os.path.split(__file__) lowerCamelCase__ = os.path.join(RES...
365
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase ): if len(_UpperCamelCase ) <= 1: return lst __lowerCAmelCase : str = 1 while i < len(_UpperCamelCase ): if lst[i - 1] <= lst[i]: i += 1 else: __lowerCAmelCase , __lowerCAmelCase : ...
182
0
"""simple docstring""" import re def lowercase__ ( _UpperCAmelCase ) -> str: '''simple docstring''' if len(re.findall('[ATCG]' , _UpperCAmelCase ) ) != len(_UpperCAmelCase ): raise ValueError('Invalid Strand' ) return dna.translate(...
255
"""simple docstring""" def lowercase__ ( _UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('Input value must be an \'int\' type' ) lowercase : str = 0 ...
255
1
'''simple docstring''' import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( a , uni...
331
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modelin...
331
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ : str = {'configuration_mbart': ['MBART_PRETRAINED_...
137
import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() a_ : str = logging.get_logger(__name__) def low...
137
1
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def SCREAMING_SNAKE_CASE_ ( snake_case : Tuple )-> Optional[Any]: for param in module.parameters(): _lowerCamelCase = False def SCREAMING_SNAKE_CASE_ ( )->...
366
"""simple docstring""" import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.nu...
80
0
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 a__ ( snake_case ): """simple docstring""" __lowe...
68
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, ...
110
0
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def __UpperCAmelCase ( lowercase ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: ...
30
"""simple docstring""" import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def __UpperCAmelCase ( lowercase ): """simple docstring""" _UpperCAmelCase = {} _U...
30
1
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision...
309
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils i...
342
0
from __future__ import annotations import math def a__ ( __UpperCamelCase , __UpperCamelCase ): if len(__UpperCamelCase ) != 2 or len(a[0] ) != 2 or len(__UpperCamelCase ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) SCREAMING_SNAKE_CASE_ ...
305
from collections import deque class lowerCamelCase : """simple docstring""" def __init__( self : str , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> None: SCREAMING_SNAKE_CASE_ = process_name ...
305
1
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -...
347
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __SCREAMING_SNAKE_CASE : List[str...
347
1
'''simple docstring''' import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class a__ ( lowerCamelCase_ ): def __init__( self , _UpperCamelCase , _UpperCamelCase=None , ...
199
'''simple docstring''' def _A ( snake_case , snake_case ) -> int: return int((input_a, input_a).count(0 ) != 0 ) def _A ( ) -> None: assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 )...
199
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch...
11
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistep...
71
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( I...
361
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig 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 ...
5
0
def __lowerCamelCase ( __a :str ) -> str: """simple docstring""" A__ = """""" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def __lowerCamelCase ( __...
274
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A : List[str] = input('''Enter image url: ''').strip() print(F'''Downloading image from {url} ...''') A : Any = BeautifulSoup(requests.get(url).content, '''...
274
1
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _snake_case ( _snake_case : Dict ): # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org...
314
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class snake_case_( a__ ): __UpperCamelCase = (DDPMScheduler,) def lowerCamelCase__ ( self : List[Any] , **UpperCamelCase_ :...
314
1
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class UpperCamelCase__ ( unittest.TestCase ): def lowerCAmelCase (self : List[Any] ): __a : Union[str, Any] = 1_0 def ...
216
'''simple docstring''' import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger A__ : List[str] = get_logger(__name__) A__ : str = R""" Args: input_ids (`jnp.ndarray` ...
185
0
'''simple docstring''' import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs i...
363
'''simple docstring''' from argparse import ArgumentParser from .env import EnvironmentCommand def a ( ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ :Union[str, Any] = ArgumentParser('''Diffusers CLI tool''' , usage='''diffusers-cli <command> ...
219
0
'''simple docstring''' from __future__ import annotations from collections import deque class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: __lowerCamelCase : list[dict] = [] self.adlist.a...
185
'''simple docstring''' from numpy import exp, pi, sqrt def UpperCAmelCase__ ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : float = 1.0 ) -> int: return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 ...
185
1
'''simple docstring''' import colorsys from PIL import Image # type: ignore def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): UpperCAmelCase : Optional[int] = x UpperCAmelCase : List[Any] = y for step in range(UpperCAmelCase_ )...
354
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase__ = {"configuration_van": ["VAN_PRETRAINED_CONFIG_ARCHIVE_MAP", "VanConfig"]} try: if not is_torch_available(): ...
280
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Any = ["""image_processor""", """tokenizer"""] lower...
48
import math def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> float: if ( not isinstance(_SCREAMING_SNAKE_CASE ,(int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("power_factor must be a...
48
1
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] , _lowerCamelCase : str) -> list[int]: '''simple docstring''' __UpperCamelCase : List[str] = int(_lowerCamelCase) # Initialize Result __UpperCamelCase :...
151
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accele...
151
1
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .tra...
239
'''simple docstring''' def lowerCamelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
239
1
"""simple docstring""" import json from typing import TYPE_CHECKING, 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 .tokeni...
369
"""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
0
"""simple docstring""" 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.util...
64
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" __A = args.pruning_method __A = args.threshold __A = args.mod...
15
0
def __UpperCamelCase ( lowercase__ : Optional[Any] , lowercase__ : Tuple ) -> str: '''simple docstring''' if b == 0: return 1 if (b % 2) == 0: return actual_power(__lowerCAmelCase , int(b / 2 ) ) * actual_power(__lowerCAmelCas...
361
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class __a ( __UpperCamelCase ): def __init__( self : Union[str, Any] , *UpperCAmelCase : Optional[Any] , *...
28
0