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 argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.u...
252
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe ...
252
1
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def _snake_case ( _snake_case : int ): # picklable ...
355
"""simple docstring""" 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_te...
314
0
"""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 _snake_case = logging.get_logger(__name__) ...
294
'''simple docstring''' import os import sys import unittest lowercase : Dict = 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: E40...
3
0
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, defa...
62
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 UpperCAmelCase_ : Any = logging.get_logger(__name__) UpperCAmelCase_ : Opt...
62
1
class _UpperCamelCase : def __init__( self :int ) -> int: UpperCAmelCase__ = {} def UpperCAmelCase_ ( self :str ) -> Optional[Any]: print(self.vertex ) for i in self.vertex: print(__lowerCamelCase , " -> " , ...
169
from __future__ import annotations import math def UpperCamelCase__( UpperCamelCase__ : int )->bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, ...
193
0
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) lowerCAmelCase_ = 2_9_9_7_9_2_4_5_8 # Symbols lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = symbols('''ct x y z''') def lowerCamelCase_ ( _UpperCam...
279
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCAmelCase_ = TypeVar('''KEY''') lowerCAmelCase_ = TypeVar('''VAL''') @dataclass(frozen=_a, slots=_a ) class __lowerCAmelCase ( Generic[KEY, VAL] ): l...
279
1
from math import ceil def __UpperCAmelCase ( __a : int ,__a : Any ) -> Union[str, Any]: """simple docstring""" _a : List[Any] = list(range(0 ,__a ) ) _a : int = [item for sublist in list(device_map.values() ) for item in sublist] ...
235
import logging from transformers import PretrainedConfig a__ = logging.getLogger(__name__) a__ = { '''bertabs-finetuned-cnndm''': '''https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json''', } class UpperCAmelCase_ ( __...
235
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, ...
350
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft...
232
0
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig __A =logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE : def __init__( self , lowercase , lo...
19
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Union[str, Any] = { '''and...
314
0
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowercase : int = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership functi...
294
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'to...
294
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMi...
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(request...
62
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_av...
360
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _UpperCAmelCase = '▁' _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = ...
328
0
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : Optional[Any] = ArgumentParser( ...
279
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> tuple[float, list[float]]: """simple docstring""" snake_case_ : Dict = list(range(len(_UpperCamelCase ) ) ) snake_case_ : Dict ...
279
1
"""simple docstring""" import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class lowercase( __a , unittest.TestCase ): '''sim...
132
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : Union[str, Any] = [] _snake_case : Dict = set({"""(""", """[""", """{"""} ) _snake_case : Union[str, Any] = set({""")""",...
132
1
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, ImageInput, PILImageResampl...
123
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : List[str] = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalD...
232
0
import warnings warnings.warn( '''memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: ''' '''`from accelerate import find_executable_batch_size` to avoid this warning.''', FutureWarning, )
218
import argparse import copy def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = {} with open(_A ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE__ = [] ...
218
1
"""simple docstring""" import unittest from knapsack import knapsack as k class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : str ) -> Optional[int]: _a : List[Any] = 0 _a : Any ...
294
"""simple docstring""" import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_s...
294
1
"""simple docstring""" import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.prepro...
370
"""simple docstring""" import qiskit def SCREAMING_SNAKE_CASE__ ( snake_case : int , snake_case : int )-> qiskit.result.counts.Counts: '''simple docstring''' UpperCAmelCase__ : str = qiskit.Aer.get_backend("aer_simulator" ) UpperCAme...
298
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "microsoft/unispeech-large-1500h-cv": ( "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config....
10
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, ) from ...
328
0
"""simple docstring""" import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class __a (tf.keras.optimizers.schedules.LearningRateSchedule): ...
56
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> bool: if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
56
1
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase ) -> list: if len(__lowerCAmelCase ) == 0: return [] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = min(__lowerCAmelCase ...
132
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.ut...
132
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
191
from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : complex , SCREAMING_SNAKE_CASE__ : str = "x" , SCREAMING_SNAKE_CASE__ : float = 10**-10 , SCREAMING_SN...
191
1
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time _lowerCAmelCase : Optional[Any] = Lock() def UpperCamelCase_( _snake_case : List[str] , _snake_case : Optional[int] , _s...
218
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say th...
218
1
"""simple docstring""" 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 tra...
226
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { """EleutherAI/gpt-neox-20b""": """https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json""", ...
226
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils i...
41
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _lowerCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for...
298
0
'''simple docstring''' import math import sys def SCREAMING_SNAKE_CASE( __lowercase ) -> int: if number != int(__lowercase ): raise ValueError('''the value of input must be a natural number''' ) if number < 0: raise ValueError('''the value of input must not be a ne...
366
'''simple docstring''' 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 fro...
334
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision fro...
56
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow ...
56
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(__SCREAMING_SNAKE_CASE ) - ngram_size + 1 )] if __na...
264
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(__SCREAMING_SNAKE_CASE ) ) if txt[a].isalpha() ...
264
1
"""simple docstring""" from math import isqrt, loga def __lowerCamelCase ( a_ : int ) -> list[int]: __SCREAMING_SNAKE_CASE :str = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: ...
191
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def __lowerCamelCase ( a_ : ...
191
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer __lowerCamelCase = logging.get_logger(__name_...
367
'''simple docstring''' from __future__ import annotations from typing import Any def UpperCAmelCase__ ( UpperCAmelCase__ ) -> int: if not postfix_notation: return 0 A_ = {"""+""", """-""", """*""", """/"""} A_ = [] for token in postfix_notati...
101
0
import sys 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 check...
226
from __future__ import annotations class UpperCAmelCase__ : '''simple docstring''' def __init__( self : Optional[Any] , a_ : Optional[int]=None ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = data ...
226
1
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def SCREAMING_SNAKE_CASE ( lowercase_ = "isbn/0140328726" ) -> dict: """simple docstring""" A__ = olid.strip().strip('''/''' ) # Remove leading/trailing whit...
351
from __future__ import annotations from typing import Any class UpperCamelCase_ : '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float = 0) ->None: '''simple d...
231
0
'''simple docstring''' import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from tran...
198
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be sm...
334
0
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[Any] = HfArgumentParser(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = pars...
56
"""simple docstring""" from ..utils import DummyObject, requires_backends class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""transformers""", """torch""", """note_seq"""] def __init__( self , *_a , **_a ) ...
56
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCAmelCase ( lowerCAmelCase__): _lowerCAmelCase : Any = ["""image_processor""", """tokenizer"""] _lowerCAmelCase : Optional[Any]...
264
"""simple docstring""" import sys lowercase__ : Dict = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557'''...
264
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 lowercase__ = logging.get_logger(__name__) lowercase__ ...
368
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if ...
280
0
"""simple docstring""" from __future__ import annotations UpperCAmelCase__ : str = "#" class lowerCAmelCase_ : """simple docstring""" def __init__(self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CA...
25
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = ('''dense.weight''', '''attention.self.qu...
101
0
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 f...
351
"""simple docstring""" def _lowerCAmelCase ( lowercase_ ): if not isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = F"""Input value of [number={number}] must be an integer""" raise TypeError(lowercase_ ) if number < 1: ...
181
0
from __future__ import annotations import math def lowerCamelCase__ ( __lowerCAmelCase : int ): """simple docstring""" if num <= 0: lowerCAmelCase_ = F"""{num}: Invalid input, please enter a positive integer.""" raise ValueError(__lowerCAmelCase ) lowerCAmelCase...
231
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) _A = { "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Spee...
231
1
"""simple docstring""" def a__ ( __SCREAMING_SNAKE_CASE ) -> Tuple: __lowerCAmelCase: List[Any] = [] __lowerCAmelCase: int = set({"(", "[", "{"} ) __lowerCAmelCase: Optional[Any] = set({")", "]", "}"} ) __lowerCAmelCase: Optional[int] = ...
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
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a : Optional[Any] = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', ...
56
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a : Tuple = { 'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP'...
56
1
import math def _SCREAMING_SNAKE_CASE ( lowercase : int ): '''simple docstring''' lowerCamelCase_ = 0 lowerCamelCase_ = 0 while num > 0: lowerCamelCase_ = num % 8 lowerCamelCase_ = octal...
208
from ..utils import DummyObject, requires_backends class A( metaclass=UpperCamelCase ): '''simple docstring''' UpperCamelCase = ['''transformers''', '''torch''', '''note_seq'''] def __init__( self : Any , *A_ : Any , **A...
208
1
"""simple docstring""" import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing im...
290
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils im...
280
0
from __future__ import annotations def lowercase__ ( __snake_case : Any ): '''simple docstring''' UpperCAmelCase_ : Any = str(__lowerCamelCase ) return len(__lowerCamelCase ) == 9 and set(__lowerCamelCase ) == set('123456789' ) ...
351
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested...
145
0
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = (DDPMParallelScheduler,) def __UpperCAm...
107
'''simple docstring''' import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProc...
181
0
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available...
64
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_r...
64
1
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ....
108
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test,...
108
1
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split a__ = datasets.load_iris() a__ = np.array(data['''data''']) a__ = np.array(data['''target''']) a__ = data['''target_names'''] a__ , a__ , a...
15
from math import ceil def __UpperCAmelCase ( __a : int = 1_001 ) -> int: """simple docstring""" _a : Dict = 1 for i in range(1 ,int(ceil(n / 2.0 ) ) ): _a : int = 2 * i + 1 _a : ...
15
1
'''simple docstring''' import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class lowerCamelCase_ ( pl.LightningModule ): """simple docstring""" def _...
208
'''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...
208
1
import math from datetime import datetime, timedelta def lowercase( UpperCamelCase_ ) -> Dict: '''simple docstring''' UpperCamelCase = year % 19 UpperCamelCase = year % 4 UpperCamelCase = year % 7 UpperCamelCase = math.floor(year / 100 ) Up...
369
def lowercase( UpperCamelCase_ ) -> int: '''simple docstring''' UpperCamelCase = len(UpperCamelCase_ ) UpperCamelCase = len(matrix[0] ) UpperCamelCase = min(UpperCamelCase_ , UpperCamelCase_ ) for row in range(UpperCamelCase_ ): # Check if dia...
165
0
import os import sys import unittest lowercase : Optional[Any] = 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_te...
20
'''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 = logging.get_logger(__name__) __...
145
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : List[str] = {"configuration_ibert": ["IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "IBertConfig", "IBertOnnxConfig"]} try: if not is_torch_available(): raise Optional...
367
import argparse import os import torch from transformers.utils import WEIGHTS_NAME _snake_case : Union[str, Any] = ["small", "medium", "large"] _snake_case : List[Any] = "lm_head.decoder.weight" _snake_case : Optional[Any] = "lm_head.weight" def lowerCAmelCase_ ...
134
0
"""simple docstring""" import os from typing import Dict, List, Tuple, TypeVar, Union A_ = TypeVar('''T''') A_ = Union[List[T], Tuple[T, ...]] A_ = Union[T, List[T], Dict[str, T]] A_ = Union[str, bytes, os.PathLike]
64
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger...
64
1
"""simple docstring""" from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __lowerCamelCase = TypeVar("T") def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" return (position...
154
"""simple docstring""" import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class UpperCamelCase__( unittest.TestCase ): def snake_case__ ( self ) -> Optional[int]: ...
154
1
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split SCREAMING_SNAKE_CASE :str = datasets.load_iris() SCREAMING_SNAKE_CASE :Dict = np.array(data['data']) SCREAMING_SNAKE_CASE :Union[str, Any] ...
15
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
15
1
"""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_prop...
76
"""simple docstring""" import os from collections.abc import Iterator def _snake_case ( UpperCamelCase : str = "." ): for dir_path, dir_names, filenames in os.walk(UpperCamelCase ): UpperCAmelCase : List[Any] = [d for d in dir_names if d != """scripts""" and d[0] not in...
76
1
from PIL import Image def _UpperCAmelCase ( snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = (2_59 * (level + 2_55)) / (2_55 * (2_59 - level)) def contrast(snake_case ) -> int: return int(1_28 + factor * (c - 1_28) ) return img....
82
"""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
0
'''simple docstring''' def __magic_name__ ( A ) -> Optional[Any]: snake_case = len(A ) while cur > 1: # Find the maximum number in arr snake_case = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi snake_case = arr[mi::-1] + arr[mi + 1 ...
332
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { "roberta-base": "https://h...
332
1
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, Timeste...
81
'''simple docstring''' 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, ) __snake_case : Optional[Any] = {'con...
134
0
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "sample_size": 32, "in_channels": 3, "out_channels": 3, "laye...
351
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, Fl...
339
0
# Function to print upper half of diamond (pyramid) def __UpperCamelCase ( _A : Union[str, Any] ) ->List[Any]: """simple docstring""" for i in range(0 , _A ): for _ in range(0 , n - i - 1 ): # printing spaces print(""" """ , ...
154
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __A : int = {'configuration_unispeech': ['UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP', 'UniSpeechConfig']} try: if not is_tor...
154
1
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') UpperCamelCase = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) UpperCamelCase = reque...
369
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments ...
221
0
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor a_ = logging.get_logger(__name__) class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : int , *a : L...
76
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_res...
76
1
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer a : Tuple = logging.get_logger(__name_...
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""" def lowercase__ ( snake_case_ :str ): __UpperCAmelCase = len(snake_case_ ) while cur > 1: # Find the maximum number in arr __UpperCAmelCase = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi __UpperCAmelCase = arr[mi::-...
332
"""simple docstring""" import heapq as hq import math from collections.abc import Iterator class _UpperCAmelCase : def __init__( self : Union[str, Any] , _lowercase : Optional[Any] ): __UpperCAmelCase = str(id_ ) __UpperCAmelCase = None ...
332
1
import argparse from collections import defaultdict import yaml __lowerCAmelCase = '''docs/source/en/_toctree.yml''' def snake_case_ ( snake_case ) -> Optional[int]: lowercase__: List[Any] = defaultdict(a_ ) lowercase__: Union[st...
364
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeatur...
288
0
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE_: Dict =logging.get_logger(__name__) SCREAMING_SNAK...
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, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import ...
339
0
from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration a : Dict = HfArgumentParser(InitializationArguments) a : Union[str, Any] = parser.parse_args() # Load codeparrot tokeniz...
368
"""simple docstring""" from __future__ import annotations class __UpperCAmelCase: """simple docstring""" def __init__( self , snake_case__=None ): '''simple docstring''' lowercase__ : Union[str, Any]= data ...
150
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a__ : List[Any] = { 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'conf...
80
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase = { "configuration_chinese_clip": [ "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "Chinese...
221
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = { 'configuration_blenderbot': [ ...
187
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as tr...
187
1
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup A__ = """https://www.indeed.co.in/jobs?q=mobile+app+development&l=""" def _UpperCAmelCase ( snake_case = "mumbai" ): """simple docstring""" _lowerCAmelC...
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
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase : int = logging.get_logger(__name__) _lowercase ...
91
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowerCamelCase__ ( A : int , A : int , A : int , A : int , A : int , A ...
91
1
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _snake_case( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : np.ndarray ) -> float: '''simple docstring''' return math.sqrt(sum...
7
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ ...
288
0
def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> int: """simple docstring""" UpperCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = len(matrix[0] ) UpperCamelCase_ = min(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for row in range...
352
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): ...
60
0
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from t...
121
"""simple docstring""" import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, ...
150
0
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_pat...
362
'''simple docstring''' from collections.abc import Sequence def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase ): return sum(c * (x**i) for i, c in enumerate(__lowerCAmelCase ) ) def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase ): _UpperCAmelCase ...
322
0
lowercase__ : Optional[Any] = 0 # The first color of the flag. lowercase__ : List[Any] = 1 # The second color of the flag. lowercase__ : Dict = 2 # The third color of the flag. lowercase__ : Optional[Any] = (red, white, blue) def lowerCa...
187
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): impor...
187
1
import string def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> str: lowercase__ = '' for i in sequence: lowercase__ = ord(_SCREAMING_SNAKE_CASE ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: ...
269
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def __UpperCamelCase () -> str: import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as or...
269
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timeste...
91
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class ...
91
1
from __future__ import annotations def a ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" return [ord(SCREAMING_SNAKE_CASE_ ) - 9_6 for elem in plain] def a ( SCREAMING_SNAKE_CASE_ : list[int] ): ...
315
import glob import os import random from string import ascii_lowercase, digits import cva __UpperCAmelCase : Optional[int] = "" __UpperCAmelCase : Union[str, Any] = "" __UpperCAmelCase : Optional[int] = "" __UpperCAmelCase : Any = 1 # (0 is vertical, 1 is horizontal) de...
315
1
'''simple docstring''' def __magic_name__( lowerCamelCase): if not isinstance(_snake_case, _snake_case): raise TypeError('''only integers accepted as input''') else: __lowerCAmelCase = str(abs(_snake_case)) __lowerCAmelCase = [l...
174
"""simple docstring""" import inspect 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_config_docstrings.py snake_case__ : Optional[Any] = '''src/transfo...
60
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case : Dict = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available()...
370
from scipy.stats import pearsonr import datasets snake_case : Tuple = "\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that eac...
41
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available()...
48
import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class A_ ( tf.keras.optimizers.schedules.LearningRateSchedule ): ...
322
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, ...
352
"""simple docstring""" from ...processing_utils import ProcessorMixin class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''WhisperFeatureExtractor''' a__ ='''WhisperTokenizer''' def __init__( self , A , A ) -> Any: super().__i...
68
0
"""simple docstring""" import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel _...
269
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot f...
269
1
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEA...
319
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import loggin...
319
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configura...
315
"""simple docstring""" from __future__ import annotations import collections import pprint from pathlib import Path def _snake_case ( _snake_case : str ) -> str: '''simple docstring''' return "".join(sorted(_snake_case ) ) def ...
315
1
'''simple docstring''' import unittest import numpy as np from transformers import RoFormerConfig, 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_avail...
246
'''simple docstring''' import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common ...
246
1
'''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 lowercase_ = False class __A ( unittest.TestCase ): '''simple docstring...
211
'''simple docstring''' class _lowercase : def __init__( self: Optional[Any] ): lowerCamelCase__ : dict[str, TrieNode] = {} # Mapping from char to TrieNode lowerCamelCase__ : List[str] = False ...
41
0
'''simple docstring''' import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowerCAmelCase : Dict = logging.get_logger(__name__) lowerCAmelCase : str = {name: getattr(...
353
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase : Optional[Any] = logging.get_logger(__nam...
251
0
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docst...
44
def lowerCAmelCase__ ( ) -> Any: '''simple docstring''' for n in range(1 , 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple ) -> Any: '''simple docstring''' A__ = 1 A__ ...
68
0
"""simple docstring""" def _snake_case ( UpperCAmelCase_ : int , UpperCAmelCase_ : bool = False ): if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit ...
69
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE_ : List[str] = '\\n@inproceedings{snover-etal-2006-study,\n title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n a...
69
1
'''simple docstring''' 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 ...
319
'''simple docstring''' import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPP...
319
1
'''simple docstring''' import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''vocab_file''': ''...
350
'''simple docstring''' import requests UpperCamelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def SCREAMING_SNAKE_CASE( __lowercase ) -> None: # fetching a list of articles in json format A: Tuple = requests.get(_NE...
334
0
"""simple docstring""" import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace...
246
"""simple docstring""" def UpperCamelCase ( _lowerCAmelCase : int ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 _UpperCAmelCase : Optional[Any] = 1 _UpperCAmelCase : List[str] = 1 while repunit: _UpperCAmelCase : Tuple = ...
246
1
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as...
327
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_uti...
327
1
def _A ( SCREAMING_SNAKE_CASE__ : List[Any] ): UpperCamelCase :Union[str, Any] = 1 UpperCamelCase :Any = 2 while i * i <= n: UpperCamelCase :str = 0 while n % i == 0: n //= i multiplicity += 1 n...
259
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase_ = { "configuration_maskformer": ["MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "MaskFormerConfig"], ...
251
0
'''simple docstring''' 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 acc...
369
'''simple docstring''' def UpperCamelCase_( snake_case : int , snake_case : int ): '''simple docstring''' while b: snake_case_ , snake_case_ = b, a % b return a def UpperCamelCase_( snake_case : int ,...
92
0
"""simple docstring""" # 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 # # Unl...
69
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __Up...
69
1
"""simple docstring""" import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to...
80
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, ...
80
1