code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import torch from torch import nn class A_ ( nn.Module ): '''simple docstring''' def __init__( self : str , lowercase_ : List[Any] , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : Dic...
151
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowercase__ = {"processing_layoutxlm": ["Layou...
151
1
from __future__ import annotations from collections import namedtuple def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> tuple: """simple docstring""" UpperCamelCase : Union[str, Any] = namedtuple("result" , "nam...
353
import math def A_ ( _lowerCAmelCase ) -> list: UpperCamelCase : str = [True] * n UpperCamelCase : Optional[int] = False UpperCamelCase : str = False UpperCamelCase : List[Any] = True for i in range(3 , int(n**0.5...
140
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.util...
326
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 lowerCAmelCase__( lowercase : Dict ) -> str: # picklable for multip...
326
1
"""simple docstring""" import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = ...
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 timm.data import resolve_data_config from timm.data.transforms_factory import create_transform fr...
226
0
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () _UpperCamelCase : Optional[Any] = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets ...
77
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def a_ ( _lowerCAmelCase : str ): '''simple docstring''' lowercase__ : int = args.pruning_method ...
77
1
from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...tes...
281
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case : Any = {'''configuration_van''': ['''VAN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VanConfig''']} try: if not is_torch_available(): raise...
281
1
from __future__ import annotations import numpy as np def _UpperCAmelCase (UpperCamelCase__ : list[float] ): return np.maximum(0 , UpperCamelCase__ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
11
"""simple docstring""" import os from collections.abc import Iterator def __SCREAMING_SNAKE_CASE ( A_ = "." ): for dir_path, dir_names, filenames in os.walk(A_ ): lowerCAmelCase__ : str = [d for d in dir_names if d != '''scripts''' and d[0] not in '''._'''] for filename in filenames: i...
106
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformer...
355
'''simple docstring''' # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils ...
91
0
from importlib import import_module from .logging import get_logger UpperCAmelCase__ = get_logger(__name__) class lowercase_ : '''simple docstring''' def __init__( self : int , __UpperCAmelCase : Optional[int]...
0
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _UpperCAmelCase = version.parse(importlib_metadata.version("""nltk""")) if NLTK_VERSION >= version.Version("""3.6.4"""): from nltk import word_tokenize _UpperCAmelCa...
140
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all Tr...
167
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image...
167
1
"""simple docstring""" import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def _A ( lowercase , lowercase=() , lowercase=None , lo...
81
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, P...
226
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def a ( lowerCamelCase__ ): '''simple docstring''' if "img_encoder.pos_embed" in name: A_ : List[str] = ...
370
'''simple docstring''' import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class _lowerCAmelCase : @property def _a (self...
135
0
def lowerCAmelCase_ ( _snake_case : str ) -> list: '''simple docstring''' if n_term == "": return [] __magic_name__ : list = [] for temp in range(int(_snake_case ) ): series.append(F'''1/{temp + 1}''' if series else "1" ) return series if __name__ == "__main__"...
281
import os import unicodedata 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 : int = logging.get_logger(__name__) snake_case : List[st...
281
1
"""simple docstring""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mod...
355
"""simple docstring""" def _lowerCamelCase( a , a , a , a ): global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: __a = mf_knapsack(i - 1 , a , a , a ) else: __a = ...
268
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__nam...
47
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, ...
91
0
'''simple docstring''' from jiwer import compute_measures import datasets lowerCAmelCase__ : List[str] = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to ...
37
'''simple docstring''' from datetime import datetime as dt import os from github import Github lowerCAmelCase__ : Union[str, Any] = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def __UpperCamelCase ( ): ...
37
1
"""simple docstring""" def lowercase_ ( _UpperCAmelCase ): """simple docstring""" A_ : Any = '''''' 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 lowercase_ ( ...
167
"""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 ...
167
1
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> List[str]: """simple docstring""" a = ...
330
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCamelCase__ : Optional[int] = pd.read_csv("""sample_data.csv""", header...
330
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0'''))...
105
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
135
0
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer...
359
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
281
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase = { """configuration_git""": ["""GIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GitConfig""", """GitVisionConfig"""], """processing_git""": ...
173
"""simple docstring""" import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ = lo...
268
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( __A : list[int] ) -> int: if not numbers: return 0 if not isinstance(__A , (list, tuple) ) or not all( isinstance(__A , __A ) for number in numbers ): raise ValueError("numbers must be an iterable of int...
111
'''simple docstring''' import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset lowerCamelCase_ = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5,...
111
1
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" if not nums: raise ValueError("""List is empty""" ) return sum(UpperCamelCase ) / len(UpperCamelCase ) if __name__ == "__main__": impor...
37
'''simple docstring''' from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _lowerCAmelCase = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems...
37
1
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 : List[Any] = logging.get_logger(__name__) _lowerCamelCase : Tuple =...
355
_lowerCamelCase : List[Any] = tuple[float, float, float] _lowerCamelCase : Tuple = tuple[float, float, float] def _UpperCAmelCase (UpperCamelCase_ : Pointad , UpperCamelCase_ : Pointad ): '''simple docstring''' _lowerCAmelCase : Tuple = end_pointa[0] - en...
159
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { """configuration_blip_2""": [ """BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Blip2Config""", """Blip2QFormerConfig""", """Blip2VisionConfig"""...
330
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration a_ = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ...
330
1
'''simple docstring''' import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel A__ : List[str] = HfApi() A__ : List[str] = {} # fmt: off A__ : Optional[int] = torch.tensor([ -0.75_15, -1.68_83, 0.24_20, 0.03_00, 0.63_47, 1.3...
0
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], ...
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json', } class SCREAMING_SNAKE_CASE...
24
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin impor...
281
0
import functools def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): # Validation if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or not all(isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for day in days ): raise ...
224
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase__ = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): lowercase__ = n - k # Calculate C(n,k) for i in range(SCREAMING_SNAKE_CASE_ ): result *=...
224
1
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": __UpperCAmelCase : Dict = argparse.ArgumentParser( description=( "Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel ...
111
def A__ ( SCREAMING_SNAKE_CASE__ = 200) -> int: __snake_case: Optional[int] = [1, 2, 5, 10, 20, 50, 100, 200] __snake_case: List[Any] = [0] * (pence + 1) __snake_case: int = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(SC...
111
1
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_bloc...
352
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ ...
26
0
'''simple docstring''' from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerat...
2
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: fro...
159
0
"""simple docstring""" import torch from torch import nn class SCREAMING_SNAKE_CASE_ ( nn.Module ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=1 , ...
255
"""simple docstring""" import inspect import unittest class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self): try: import diffusers # noqa: F401 except ImportError: assert False def snake_case_ ...
255
1
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase__ = HfApi() UpperCAmelCase__ = {} # fmt: off UpperCAmelCase__ = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1...
0
from __future__ import annotations UpperCAmelCase__ = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6...
0
1
"""simple docstring""" from __future__ import annotations def a__ ( __lowercase ) -> list[int]: return [ord(__lowercase ) - 96 for elem in plain] def a__ ( __lowercase ) -> str: return "".join(chr(elem + 96 ) for elem in encoded ) ...
163
"""simple docstring""" def a__ ( __lowercase , __lowercase ) -> float: _validate_point(__lowercase ) _validate_point(__lowercase ) if len(__lowercase ) != len(__lowercase ): raise ValueError("Both points must be in the same n-dimensional space" )...
163
1
"""simple docstring""" import math class UpperCamelCase__ : """simple docstring""" def SCREAMING_SNAKE_CASE__ ( self : int , SCREAMING_SNAKE_CASE_ : list[list[float]] , SCREAMING_SNAKE_CASE_ : list[in...
224
"""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, ) lowercase__ : ...
224
1
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import...
161
"""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...
161
1
import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hu...
277
from math import asin, atan, cos, radians, sin, sqrt, tan _snake_case = 6_3_7_8_1_3_7.0 _snake_case = 6_3_5_6_7_5_2.3_1_4_2_4_5 _snake_case = 6378137 def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : Any ...
26
0
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def lowerCAmelCase__ ( ): snake_case_ : str = ArgumentParser( description=( "PyTorch...
359
import argparse import copy def lowerCAmelCase__ ( _a : List[Any] ): snake_case_ : List[Any] = {} with open(_a ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: snake_case_ : int = [] _list.append([line.spl...
36
0
"""simple docstring""" def lowercase__ ( _UpperCAmelCase , _UpperCAmelCase = False ) -> bool: '''simple docstring''' 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): #...
255
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers...
255
1
"""simple docstring""" UpperCAmelCase : Optional[Any] = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter...
320
"""simple docstring""" UpperCAmelCase : Dict = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' def lowerCamelCase ( _UpperCamelCase : bytes ) -> bytes: '''simple docstring''' if not isinstance(_UpperCamelCase , _UpperCamelCase ...
320
1
'''simple docstring''' import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKE...
163
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) ...
163
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/config.json""", """funnel-transfo...
192
import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor _UpperCAmelCase = logging.get_logger(__name__) class UpperCAmelCase ( __A ): '''simple docstring''' def __init__( self , *lowercase , **lowe...
192
1
'''simple docstring''' import os import string import sys a__ : int = 1 << 8 a__ : Optional[Any] = { "tab": ord("\t"), "newline": ord("\r"), "esc": 2_7, "up": 6_5 + ARROW_KEY_FLAG, "down": 6_6 + ARROW_KEY_FLAG, "right": 6_7 + ARR...
161
'''simple docstring''' from __future__ import annotations def snake_case ( UpperCAmelCase )-> list[int]: """simple docstring""" __A = 2 __A = [] while i * i <= n: if n % i: i += 1 els...
161
1
"""simple docstring""" import os from distutils.util import strtobool def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Optional[Any] ) ->List[str]: for e in env_keys: A__ : List[Any] = int(os.environ.get(UpperCAme...
296
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets A_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel...
296
1
import math def _a ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] ) -> List[Any]: """simple docstring""" if ( not isinstance(_lowerCamelCase , (int, float) ) or power_factor < -1 or power_factor > 1 ...
340
import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import...
36
0
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils imp...
135
'''simple docstring''' import os import unicodedata 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 SPIECE_UNDERLINE, logging lowerCamelCase :Union[str, An...
135
1
"""simple docstring""" # flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_...
320
"""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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, ...
320
1
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.sche...
368
"""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...
161
0
def UpperCamelCase (lowercase_: str = "The quick brown fox jumps over the lazy dog" , ) -> bool: A__ : str = set() # Replace all the whitespace in our sentence A__ : List[str] = input_str.replace(""" """ , """""" ) for alpha in input_str: ...
192
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""...
192
1
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( ...
360
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 convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_...
119
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils ...
296
from collections import defaultdict from math import gcd def __lowercase ( _SCREAMING_SNAKE_CASE = 1_50_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = 2 while 2 * euc...
296
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be consider...
357
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def A(__a: Any , __a: Union[str, Any] , __a: List[str] ): lowerCAmelCase_ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelle...
22
0
"""simple docstring""" import numpy as np def lowercase_ ( _lowerCamelCase: np.array ) -> np.array: '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowercase_ ( _lowerCamelCase: np.array ) -> np.array: ''...
135
"""simple docstring""" __A = [0, 2, 4, 6, 8] __A = [1, 3, 5, 7, 9] def lowercase_ ( _lowerCamelCase: int , _lowerCamelCase: int , _lowerCamelCase: list[int] , _lowerCamelCase: int ) -> int: '''simple docstring''' if remaining_length ==...
135
1
from __future__ import annotations from collections import deque class UpperCamelCase : '''simple docstring''' def __init__( self , UpperCamelCase_ ): lowercase_ :list[dict] = [] self.adlist.append( {...
369
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional ...
252
0
import re def UpperCamelCase( __UpperCamelCase : str ): lowerCAmelCase_ : str = re.compile(R'''^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$''' ) if match := re.search(__UpperCamelCase ,__UpperCamelCase ): return match.string == phone return False if __name__ == "__main__": pr...
103
'''simple docstring''' from __future__ import annotations def snake_case ( UpperCAmelCase )-> list[int]: """simple docstring""" __A = 2 __A = [] while i * i <= n: if n % i: i += 1 els...
161
0
"""simple docstring""" from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 snake_case__ : int = { # 1536-bit 5: { ...
314
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging snake_case__ : List[str] = logging.get_logger(__name__) class snake_case_( a__ ): ...
314
1
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetP...
28
import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import loggi...
119
0
"""simple docstring""" from numpy import exp, pi, sqrt def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase = 0.0 , UpperCAmelCase = 1.0 ) ->int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": ...
303
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common i...
303
1
'''simple docstring''' from __future__ import annotations def __UpperCamelCase ( lowercase__ : float, lowercase__ : float, lowercase__ : float ): '''simple docstring''' if days_between_payments <= 0: raise ValueError('days_between_payments must be > ...
141
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import T...
22
0
'''simple docstring''' def __a ( UpperCAmelCase ) ->int: """simple docstring""" if not isinstance(UpperCAmelCase , UpperCAmelCase ): A = f"""Input value of [number={number}] must be an integer""" raise TypeError(UpperCAmelCase ) if number < 1: A ...
337
'''simple docstring''' import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' ...
337
1
'''simple docstring''' import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness a_ : Optional[int] = "\\n@misc{chen2021evaluating,\n...
55
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : int = { "configuration_autoformer": [ "AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "AutoformerConfig", ], }...
252
0
# Lint as: python3 import itertools import os import re A_ : Dict = re.compile(r'([A-Z]+)([A-Z][a-z])') A_ : List[str] = re.compile(r'([a-z\d])([A-Z])') A_ : Optional[int] = re.compile(r'(?<!_)_(?!_)') A_ : Tuple = re.compile(r'(_{2,})') A_ : Tuple = r'^\w+(\...
361
# 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 a...
292
0
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNeta...
299
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = { '''kssteven/ibert-roberta-base''': ...
313
0
import argparse import os import re UpperCAmelCase__ = 'src/transformers' # Pattern that looks at the indentation in a line. UpperCAmelCase__ = re.compile(r'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. UpperCAmelCase__ = re.compile(r'^\s*\"([^\"]+)\":') #...
361
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ...
40
0
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class __UpperCamelCase : """simple docstring""" def UpperCAmelCase__ ( self : Any , _A : Any ): """simple...
303
import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def a__ ( snake_case , snake_case=False ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = OmegaConf.load(snake_case ) if display: print(yaml.dump(Om...
303
1
from __future__ import annotations def __UpperCamelCase ( _A ): lowerCAmelCase_ = len(_A ) # We need to create solution object to save path. lowerCAmelCase_ = [[0 for _ in range(_A )] for _ in range(_A )] lowerCAmelCase_ = run_maze(_A , 0 , ...
167
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host...
167
1
def __lowercase ( _UpperCamelCase ) ->int: """simple docstring""" if not isinstance(_UpperCamelCase, _UpperCamelCase ): lowercase : List[str] = f"""Input value of [number={number}] must be an integer""" raise TypeError(_UpperCamelCase ) ...
337
from typing import List from .keymap import KEYMAP, get_character def __lowercase ( _UpperCamelCase ) ->int: """simple docstring""" def decorator(_UpperCamelCase ): lowercase : str = getattr(_UpperCamelCase, '''handle_key''', [] ) han...
337
1
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedTo...
25
'''simple docstring''' def lowercase (): """simple docstring""" _lowerCAmelCase : Optional[int] = [3_1, 2_8, 3_1, 3_0, 3_1, 3_0, 3_1, 3_1, 3_0, 3_1, 3_0, 3_1] _lowerCAmelCase : int = 6 _...
25
1
import baseaa def __snake_case ( _UpperCAmelCase ): return baseaa.aaaencode(string.encode('''utf-8''' ) ) def __snake_case ( _UpperCAmelCase ): return baseaa.aaadecode(_UpperCAmelCase ).decode('''utf-8''' ) if __name__ == "__main__": import doctest doctest.test...
49
"""simple docstring""" from __future__ import annotations _snake_case : str = [] def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): for i in range(len(UpperCamelCase ) ): if board[row][i] == 1: retur...
292
0
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thu...
41
def lowerCAmelCase_ ( _snake_case : int , _snake_case : Optional[int] ) -> List[Any]: '''simple docstring''' return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Option...
41
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 = get_tests_dir() + "/test_...
10
"""simple docstring""" from bisect import bisect from itertools import accumulate def lowercase ( A_ , A_ , A_ , A_ )-> Union[str, Any]: '''simple docstring''' a : Any = sorted(zip(A_ , A_ ) , key=lambda A_ ...
40
0
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatc...
360
"""simple docstring""" def UpperCamelCase_ ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : str ) -> List[Any]: """simple docstring""" return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def UpperCamelCase_ ...
289
0
"""simple docstring""" def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" if index == number_of_items: return 0 A_ : Tuple = 0 A_ ...
167
"""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 ...
167
1
"""simple docstring""" def lowerCamelCase_ (UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] ): return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def lowerCamelCase_ (UpperCamelCase__ : str , UpperCamelCase__ : str=0 ): ...
68
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class _UpperCAmelCase : '''simple docstring''' def __init__( self ) -> Tuple: _UpperCAmelCase : str = {} def __lo...
68
1
"""simple docstring""" import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class lowerCAmelCase_ : """simple docstring""" def __init__(self , SCREAMIN...
25
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ArgumentParser( ...
25
1
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() pars...
129
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSc...
129
1
'''simple docstring''' 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, i...
41
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixi...
41
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, TimestepE...
361
'''simple docstring''' def _A (lowerCAmelCase__ :list[int] , lowerCAmelCase__ :list[int] ) -> None: '''simple docstring''' _a = len(lowerCAmelCase__ ) print('The following activities are selected:' ) # The first a...
104
0
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokeniz...
25
"""simple docstring""" from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ...
289
0
import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py UpperCamelCase = '''src/transformers''' # This is to make sure the transformers m...
125
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __lowerCamelCase ( snake_case__ ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE = prime_factors(snake_case__ ) if is_square_free(...
125
1
from __future__ import annotations def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[int] , SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: int ) -> None: '''simple docstring''' if (direction == 1 and array[in...
68
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, ge...
68
1
"""simple docstring""" 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 ( ...
364
"""simple docstring""" from itertools import product def __UpperCAmelCase ( lowercase ,lowercase ): """simple docstring""" _UpperCAmelCase = sides_number _UpperCAmelCase = max_face_number * dice_number _UpperCAmelCase = [0] * (max_total + 1) _UpperCAmelCase = 1 _U...
30
0
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_to...
129
import gc import math import unittest import torch from diffusers import UNetaDModel from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin __sn...
129
1
"""simple docstring""" def lowerCamelCase_ ( UpperCamelCase__ : bytes ) -> str: """simple docstring""" return "".join([hex(lowercase__ )[2:].zfill(2 ).upper() for byte in list(lowercase__ )] ) def lowerCamelCase_ ( UpperCam...
356
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...
348
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: if not isinstance(A__ , A__ ): raise ValueError("""check_bouncy() accepts only integer arguments""" ) snake_case_ = str(A__ ) snake_case_ = """""".join(sorted(A__ ) ) ret...
347
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from tr...
104
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
105
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import...
105
1
'''simple docstring''' import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration snake_case_ : Union[str, Any] = 50_00_00 snake_case_ ,snake_case_ : Optional[int] = os.path.split(__file__) snake_case_ : O...
125
'''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 snake_case_ : List[str] = logging...
125
1
def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def lowerCamelCase__ ( _lowercase , _lowercase=0 ): '''simple docstring''' return sorted(_lowercase ...
235
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...tes...
235
1
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) ...
80
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import t...
30
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 ( ...
72
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data imp...
72
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase : Optional[int] = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { "ut/deta": "http...
28
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __snake_case = 4 __snake_case = 3 class __snake_case ( lowerCamelCase__ ): pass d...
348
0
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def __snake_case( _lowerCAmelCase ) -> Any: snake_cas...
43
'''simple docstring''' import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PA...
43
1
"""simple docstring""" class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict ) ->str: """simple docstring""" ...
347
'''simple docstring''' import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL lowerCAmelCase__ = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def _A ( ...
104
0
"""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'], 'co...
354
"""simple docstring""" from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def _snake_case ( lowercase__ : bool = True , *lowercase__ : Optional[int] , **lowercase__ : s...
1
0
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils imp...
235
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : List[Any] = (DDPMScheduler,) def __lowercase ( sel...
235
1
'''simple docstring''' def __magic_name__( lowerCamelCase): __lowerCAmelCase = 1 __lowerCAmelCase = 2 while i * i <= n: __lowerCAmelCase = 0 while n % i == 0: n //= i multiplicity +=...
364
'''simple docstring''' import numpy as np def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase = 1E-12, lowerCamelCase = 1_0_0, ): assert np.shape(lowerCamelCase)[0] == np.shape(lowerCamelCase)[1] # Ensure proper dimensionality. assert np.shape(lowerCamelCa...
9
0
"""simple docstring""" lowerCAmelCase__ = [0, 2, 4, 6, 8] lowerCAmelCase__ = [1, 3, 5, 7, 9] def snake_case_ ( A_ : int, A_ : int, A_ : list[int], A_ : int ): '''simple docstring''' if remaining_length == 0: ...
72
"""simple docstring""" def snake_case_ ( A_ : list[list[float]] ): '''simple docstring''' _lowerCamelCase : list[list[float]] = [] for data in source_data: for i, el in enumerate(A_ ): if len(A_ ) < i...
72
1
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mo...
362
def __lowerCamelCase (UpperCAmelCase__ : int , UpperCAmelCase__ : int ): while b: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = b, a % b return a def __lowerCamelCase (UpperCAmelCase__ : int , UpperCAmelCase__ ...
206
0
import re from filelock import FileLock try: import nltk __lowercase = True except (ImportError, ModuleNotFoundError): __lowercase = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def lowerCamelCase ( SCREAMING...
43
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational ...
43
1
import functools from typing import Any def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> bool: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ) or len(_UpperCamelCase ) == 0: raise ValueError('''the string sho...
356
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( ...
279
0