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 __future__ import annotations from random import random from typing import Generic, TypeVar lowerCAmelCase : List[Any] = TypeVar('KT') lowerCAmelCase : Tuple = TypeVar('VT') class _A ( Generic[KT, VT]): def __init__( self , _SCREAMING_SNAKE_CASE = "root...
253
"""simple docstring""" import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger lowerCamelCase_ : Dict = get_logger(__name__) lowerCamelCase_ : List[str] = r'\n Args:\n ...
286
0
from __future__ import annotations import pandas as pd def UpperCamelCase (lowercase_: list[int] , lowercase_: list[int] , lowercase_: int ) -> list[int]: A__ : Optional[int] = [0] * no_of_processes A__ : Dict = [0] * no_of_processes #...
360
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort A_ : Union[str, An...
141
0
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def ...
64
lowerCAmelCase_ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_...
279
0
"""simple docstring""" def UpperCAmelCase ( UpperCAmelCase ) -> bool: snake_case_ = [int(UpperCAmelCase ) for i in ip_va_address.split('.' ) if i.isdigit()] return len(UpperCAmelCase ) == 4 and all(0 <= int(UpperCAmelCase ) <= 254 for octet in octets ) if __name__ == "__main__": __UpperCame...
355
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .token...
312
0
'''simple docstring''' import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 __SCREAMING_SNAKE_CASE :List[Any] = 0b1_0_1_1_0_0_1...
22
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase : List[str] = { 'configuration_xlm': ['XLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMConfig', 'XLMOnnxConfig'], 'tokenization_xlm': ['XL...
88
0
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 lowerCamelCase_ : List[Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { ""...
223
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline lowerCamelCase_ : Optional[Any] = datasets.utils.logging...
223
1
def UpperCamelCase__( UpperCamelCase__ : int = 1_00_00_00 )->int: A__ = set(range(3 , UpperCamelCase__ , 2 ) ) primes.add(2 ) for p in range(3 , UpperCamelCase__ , 2 ): if p not in primes: continu...
193
def UpperCamelCase__( UpperCamelCase__ : Dict )->Dict: # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection A__ = len(UpperCamelCase__ ) A__ = ...
193
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transforme...
285
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def _snake_case( ) -> tuple[list[int], int]: lowercase : List[Any] = [randint(-1_000 , 1_000 ) for i in range(10 )] lowercase : ...
285
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): fr...
34
import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )...
195
0
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar lowercase__ :List[str] = TypeVar("T") class lowercase ( Generic[T] ): def __init__( self ...
365
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ :Dict = { "configuration_luke": ["LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP", "LukeConfig"], "tokenization_luke": ["LukeTokenizer"], } try: if not is_torch_available(): ...
97
0
'''simple docstring''' def a__ ( lowerCAmelCase__ ) -> int: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError('''Input value must be a \'int\' type''' ...
181
'''simple docstring''' 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 impor...
181
1
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import...
363
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline _lowercase : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name cla...
21
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, Blip...
182
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def A ( _lowercase ): if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE : int = version.parse(ac...
182
1
import math def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' return math.sqrt(UpperCamelCase__ ) * math.sqrt(UpperCamelCase__ ) == num def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case...
200
import requests _UpperCAmelCase : Union[str, Any] = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=""" def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case_ = requests.get(_NEWS_API + bbc_news_api_key ...
200
1
'''simple docstring''' import json import sys def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: with open(lowerCAmelCase__ , encoding='''utf-8''' ) as f: UpperCAmelCase__ : Any = json.load(lowerCAmelCase__ ) Uppe...
181
'''simple docstring''' import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing im...
181
1
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __lowerCamelCase ( snake_ca...
361
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: float , __lowerCamelCase: float , __lowerCamelCase: float , __lowerCamelCase: float , __lowerCamelCase: float , ): '''simple docstring''' lowercase_ = [redshift, radiation_density, matt...
297
0
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) lowerCAmelCase__ = models.Sequential() # Step 1 - Convolut...
130
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCAmelCase__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerC...
130
1
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def _A ( lowercase ): """simple docstring""" # vision encoder if "img_encoder.pos_embed" i...
363
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image ...
215
0
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common impo...
71
# 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 required ...
312
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ : List[str] = logging.get_logger(__name__) lowerCAmelCase_ : Union[str, ...
363
'''simple docstring''' from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available()...
346
0
from __future__ import annotations def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = [] __magic_name__ = [] __magic_name__ = 0 __magic_name__ = sum(A_ ) create_state_space_tree(A_, A_,...
88
from maths.prime_check import is_prime def __lowercase ( lowerCamelCase : int ): if not isinstance(lowerCamelCase , lowerCamelCase ): UpperCamelCase_ : List[str] = F"Input value of [number={number}] must be an integer" raise TypeError(lowerCamelCase ) if is_prime(lowerCamel...
175
0
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class lowercase ( unittest.TestCase ): def __snake_case( self : Optional[int] ) -> Any: '''sim...
206
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer _lowerCamelCase : Union[str, Any] = logging.get_logger(__nam...
206
1
"""simple docstring""" from __future__ import annotations from functools import lru_cache from math import ceil A_ = 1_00 A_ = set(range(3, NUM_PRIMES, 2)) primes.add(2) A_ = 42 for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: ...
64
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __a = { "configuration_mobilebert": [ "MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", ...
66
0
from __future__ import annotations from cmath import sqrt def UpperCAmelCase_ (_lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int ): if a == 0: raise ValueError("Coefficient 'a' must not be zero." ) __UpperCamelCase : T...
171
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available ...
171
1
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _lowercase ( __lowerCamelCase): ...
184
import sys from collections import defaultdict class A_ : '''simple docstring''' def __init__( self ): lowercase = [] def SCREAMING_SNAKE_CASE__ ( self , snake_case ): return self.node_position[vertex] def SCREAMING_SNAKE_CASE__ (...
195
0
lowercase__ =[ 'Audio', 'Array2D', 'Array3D', 'Array4D', 'Array5D', 'ClassLabel', 'Features', 'Sequence', 'Value', 'Image', 'Translation', 'TranslationVariableLanguages', ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, Cl...
361
import os import sys import unittest lowercase__ =os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_t...
90
0
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _S...
343
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def UpperCamelCase_( lowerCamelCase_ ) -> bool: _lowercase : int = int(number**0.5 ) return number == sq * sq def UpperCamelCase_( lowerCamelCase_ , lowerCam...
21
0
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCamelCase_ ( unittest.TestCase ): ...
350
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def UpperCAmelCase ( _lowerCamelCase , ...
256
0
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def UpperCamelCase () -> Optional[int]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): wi...
192
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline A_ : List[str] = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std...
192
1
"""simple docstring""" import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ...
362
"""simple docstring""" 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 fr...
100
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase__ =logging.get_logger(__name__) lowercase__ ={ 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/rof...
216
from __future__ import annotations def __UpperCamelCase ( lowerCAmelCase__ : list[float] , lowerCAmelCase__ : list[float] ): __a : Dict = sorted(numsa + numsa ) __a , __a : Optional[Any] = divmod(len(lowerCAmelCase__ ) , 2 ) if mod == 1: return all_...
216
1
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepi...
327
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_availa...
327
1
from __future__ import annotations import math def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multi...
50
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transf...
63
0
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase = logging.getLogger(__name__) def _lowerCamelCase( ) -> Optional[int]: '''simple docstring''' __lowercase= argparse.ArgumentParser( ...
365
from math import factorial, radians def _lowerCamelCase( lowercase__ , lowercase__ = 1_8 , lowercase__ = 1_0 ) -> float: '''simple docstring''' __lowercase= angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians __l...
304
0
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_im...
333
import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging A_ : Tuple = logging.get_logger(__name__) class A_ ( _a ): '''simple docstring''' ...
333
1
import math def lowerCamelCase_ ( lowerCAmelCase: float , lowerCAmelCase: float )-> int: if initial_intensity < 0: raise ValueError('The value of intensity cannot be negative' ) # handling of negative values of initial intensity if angle < 0 or angle > 3_60: raise Va...
366
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { """nielsr/canine-s""": 2048, } # Unicode defines 1,114,112 total “codepoints” lowe...
260
0
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 A_ :int = logging.get_logger(__name__) A_ :Union[str, ...
71
UpperCAmelCase__ = {} def A ( _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int: '''simple docstring''' # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late ...
339
0
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.impo...
208
def _SCREAMING_SNAKE_CASE ( lowercase : str ): '''simple docstring''' if not all(char in '01' for char in bin_string ): raise ValueError('Non-binary value was passed to the function' ) if not bin_string: raise ValueError...
208
1
'''simple docstring''' from math import pow, sqrt def lowercase_ ( *_lowercase ) -> bool: '''simple docstring''' lowerCamelCase_ : Optional[int] = len(_lowercase ) > 0 and all(value > 0.0 for value in values ) return result def lowercase_ ( _lowercase , _l...
318
'''simple docstring''' import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class __lowercase ( tf.keras.layers.Layer ): def __init__(self , ...
318
1
'''simple docstring''' from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import f...
350
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase :Dict = {'''configuration_mmbt''': ['''MMBTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvail...
135
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
91
"""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
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """facebook/timesformer""": """https://huggingface.co/facebook/timesformer/resolve/main/config.json""", } class UpperCAmel...
192
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline _UpperCAmelCase = { """n_samples""": 64, """horizon""": 32, """num_inference_steps""": 20, """n_guide_steps""": 2, # can set to 0 for faster sampling, does not use value network ...
192
1
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common...
316
"""simple docstring""" def A ( snake_case :int , snake_case :int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
316
1
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def A ( snake_case :str = "laptop" ) -> DataFrame: __UpperCamelCase = f'https://www.amazon.in/laptop/s?k={product}' __UpperCamelCase = { 'User-Agent': 'Mozilla/...
366
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import ...
263
0
"""simple docstring""" import argparse __snake_case = '''docs/source/_static/js/custom.js''' def A_ ( _lowerCAmelCase : Tuple ): """simple docstring""" with open(_lowerCAmelCase, encoding='''utf-8''', newline='''\n''' ) as f: _a = f.readlines...
320
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCamelCase ( metaclass=a__ ): '''simple docstring''' A_ : Optional[Any] = ['flax'] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: ...
320
1
"""simple docstring""" import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from...
352
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput ...
336
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _UpperCAmelCase : Optional[Any] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "B...
222
def A ( lowercase ) -> str: '''simple docstring''' return " ".join( ''.join(word[::-1] ) if len(lowercase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
222
1
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE ( A__ ): ...
360
import os import pytest from attr import dataclass __a = '''us-east-1''' # defaults region @dataclass class __SCREAMING_SNAKE_CASE : A : str A : str = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' A : Union[str, Any] ...
173
0
"""simple docstring""" import math def _snake_case ( ): lowerCAmelCase : Union[str, Any] = input('''Enter message: ''' ) lowerCAmelCase : Optional[int] = int(input(f'''Enter key [2-{len(_snake_case ) - 1}]: ''' ) ) lowerCAmelCase : str = input('''Encr...
60
'''simple docstring''' import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you shou...
304
0
'''simple docstring''' import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE (a__ , unittest.TestCase ): lowerCA...
190
'''simple docstring''' def _lowerCAmelCase ( __snake_case : str ) -> str: __A : Optional[Any] = [0] * len(__snake_case ) __A : Dict = [] __A : Optional[int] = [1] * len(__snake_case ) for values in ...
190
1
"""simple docstring""" import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.fil...
81
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransform...
302
0
from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..mod...
7
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def A (__A : BertModel , __A : str , __A : str ) -> int: """simple docstring""" UpperC...
7
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/config.json"} class _...
251
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available UpperCamelCase_ = {"configuration_speech_encoder_decoder": ["SpeechEncoderDecoderConfig"]} try: if not is_torch_a...
251
1
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx...
371
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output...
273
0
'''simple docstring''' import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem a_ : int = importlib.util.find_spec("""s3fs""") is not None if _has_safs:...
75
'''simple docstring''' from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _A : List[Any] = 299792458 # Symbols _A , _A , _A , _A : Union[str, Any] = symbols('''ct x y z''') ...
229
0
"""simple docstring""" from __future__ import annotations lowerCamelCase_ : int = 1.6_0_2_1E-1_9 # units = C def _A ( lowercase , lowercase , lowercase , ): """simple docstring""" if (conductivity, electron_conc, mobility).count(0...
215
"""simple docstring""" import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_de...
215
1
import math from numpy import inf from scipy.integrate import quad def _a ( SCREAMING_SNAKE_CASE_ : float ): if num <= 0: raise ValueError("math domain error" ) return quad(SCREAMING_SNAKE_CASE_ , 0 , SCREAMING_SNAKE_CASE_ , arg...
92
"""simple docstring""" from pathlib import Path import numpy as np from PIL import Image def lowercase ( _SCREAMING_SNAKE_CASE : np.ndarray ): '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = rg...
260
0
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _snake_case ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): _lowerCamelCas...
12
"""simple docstring""" import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() parser.add_argument( "...
12
1
"""simple docstring""" __A = { "joule": 1.0, "kilojoule": 1_000, "megajoule": 1_000_000, "gigajoule": 1_000_000_000, "wattsecond": 1.0, "watthour": 3_600, "kilowatthour": 3_600_000, "newtonmeter": 1.0, "calorie_nutr": 4_186.8, "kilocalorie_nutr"...
148
"""simple docstring""" import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_availa...
148
1
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='''%(message)s''') def SCREAMING_SNAKE_CASE_ ( __magic_name__ : np.ndarray ) -> np.ndarray: """simple docstring""" return input_array.reshape((input...
62
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if ...
62
1
"""simple docstring""" import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( Prophet...
221
"""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 ...modeling_outputs import ( BackboneOutput, BaseModelOutputWit...
221
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable a = list[list[float | int]] def _snake_case ( _snake_case : Matrix , _snake_case : Matrix ) -> Tuple: '''simple docstring''' _A = len(_...
355
"""simple docstring""" import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging a = ...
271
0
def _lowercase ( ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ = 0 for i in range(1 , 1001 ): total += i**i return str(UpperCamelCase_ )[-10:] if __name__ == "__main__": print(solution())
176
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch...
176
1
'''simple docstring''' import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( a__ ): """simple docstring""" lowerCAmelCase__ = ["image_processor", "tokenizer"] lowerCAmelCase__ = "AutoImagePro...
370
'''simple docstring''' class lowerCAmelCase__ : # Public class to implement a graph """simple docstring""" def __init__( self : Dict , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : list[list[bool]] ) -> None: """simple...
331
0
'''simple docstring''' from math import factorial class snake_case : """simple docstring""" def __init__( self : int , __A : List[str] , __A : int ): __UpperCamelCase = real if isinstance(__A , __A ): ...
53
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel __UpperCAmelCase : Any = { "text_branch": "text_model", "audio_branch": "audio_model.audio_encoder", "attn": "attention.self", "self...
111
0
from cva import destroyAllWindows, imread, imshow, waitKey def lowerCAmelCase__ ( _UpperCamelCase : Optional[int] ) -> Optional[int]: """simple docstring""" snake_case ,snake_case = img.shape[0], img.shape[1] # converting each ...
367
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def lowerCAmelCase__ ( _UpperCamelCase : int = 8 ) -> str: """simple docstring""" snake_case ...
149
0
from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models...
7
def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: '''simple docstring''' A__ = 0 A__ = len(SCREAMING_SNAKE_CASE__ ) - 1 while left <= right: ...
7
1
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) __A = logging.getLogger(__name__)...
277
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Ac...
277
1
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_comm...
93
import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __lowercase ( __lowerCAmelCase : str , __lowerCAmelCase : Any , __...
240
0
'''simple docstring''' from __future__ import annotations import collections import pprint from pathlib import Path def lowercase__ ( __UpperCamelCase )-> str: return "".join(sorted(__UpperCamelCase ) ) def lowercase__ ( __UpperCamelCase...
183
'''simple docstring''' from PIL import Image def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Image: def brightness(__UpperCamelCase ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ...
183
1
'''simple docstring''' import json import os import shutil 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 AutoConfig, BertConfig, GPTaConfig from...
27
'''simple docstring''' import re from filelock import FileLock try: import nltk __snake_case = True except (ImportError, ModuleNotFoundError): __snake_case = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def a...
97
0
from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging __a = logging.ge...
235
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __a = { 'configuration_bloom': ['BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BloomConfig', 'BloomOnnxConfig'], } try: if not is_tokenizers_available(): ...
235
1
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowerCamelCase__ ( A__ : NDArray[floataa] , A__ : NDArray[floataa] , A__ : list[int] , A__ : int , ): '''simple d...
12
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils impo...
12
1
"""simple docstring""" def _SCREAMING_SNAKE_CASE ( _lowercase : float ) ->float: '''simple docstring''' if edge <= 0 or not isinstance(_lowercase , _lowercase ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2)...
79
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def _SCREAMING_SNAKE_...
79
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 a__ : Optional[Any] = logging.get_logger(__name__)...
161
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Optional[Any] = {"UserAgent": UserAgent().random} def snake_case ( UpperCAmelCase )-> dict:...
161
1
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 lowercase_ : @property def lowerCamelCase_ ( self ): """simple doc...
261
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( a__ : Dict ) -> List[Any]: UpperCamelCase_ = {} UpperCamelCase_ ...
261
1
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from dif...
101
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, Bit...
101
1
'''simple docstring''' from collections.abc import Callable import numpy as np def _lowerCamelCase ( lowercase : Callable , lowercase : float , lowercase : float , lowercase : float , lowercase : float ) -> ...
346
'''simple docstring''' import re from filelock import FileLock try: import nltk lowerCAmelCase_ : Optional[int] = True except (ImportError, ModuleNotFoundError): lowerCAmelCase_ : Tuple = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: ...
346
1
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class a__ ( a_ ): __lowerCAmelCase = (DDPMScheduler,) def __magic_name__ ( self , **_a ): lowercase : str ...
202
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, res...
202
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : Optional[int] = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipCo...
86
"""simple docstring""" from __future__ import annotations import bisect def lowercase__ ( snake_case_ :list[int] , snake_case_ :int , snake_case_ :int = 0 , snake_case_ :int = -1 ): if hi < 0: __UpperCAmelCase = len(snake_case_ ) while lo < hi: ...
86
1
'''simple docstring''' import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" A_ : Dict = ("den...
344
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib A__: Optional[int] ...
149
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaV...
360
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-g...
258
0
'''simple docstring''' def __lowerCamelCase ( lowerCAmelCase_ = 100 ) -> int: _a : List[str] = (n * (n + 1) // 2) ** 2 _a : str = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"""{solu...
89
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', ...
89
1
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetrieve...
284
import os import pytest from attr import dataclass __SCREAMING_SNAKE_CASE : int = 'us-east-1' # defaults region @dataclass class lowercase_ : _lowerCamelCase = 42 _lowerCamelCase = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' _lowerCamelCase...
284
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_ = logging.get_logger(__name__) lowerCAmelCase_ = {'''voc...
8
"""simple docstring""" import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _SCREAMING_SNAKE_CASE : Tuple = version.parse(importlib_metadata.version('''nltk''')) if NLTK_VERSION >= versi...
183
0
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 ...
218
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[Any] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/viv...
218
1
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms....
235
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = {'''configuration_mmbt''': ['''MMBTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: p...
235
1
'''simple docstring''' from collections.abc import Iterable from typing import Generic, TypeVar UpperCAmelCase = TypeVar('_T') class __snake_case( Generic[_T] ): '''simple docstring''' def __init__( self , A_ = None ) -> None: lowerCAmelCase ...
187
'''simple docstring''' import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification ...
187
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """naver-clova-ix/donut-base""": """https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json""", # See all D...
256
"""simple docstring""" import logging from transformers import PretrainedConfig UpperCAmelCase = logging.getLogger(__name__) UpperCAmelCase = { """bertabs-finetuned-cnndm""": """https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json""", ...
256
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCamelCase ( metaclass=_A ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = ["torch"] def __init__( self ,*UpperCAmelCase_ ,**UpperCAmelCase_ ): r...
363
"""simple docstring""" UpperCAmelCase: str = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.g...
336
0
"""simple docstring""" 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 dif...
173
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) SCREAMING_SNAKE_CASE_: Optional[int] =str(bin(lowercase ) )[2:] # remove the leading "0b" ...
173
1
"""simple docstring""" # This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def _snake_case ( _snake_cas...
369
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path snake_case__ : Union[str, Any] = '''src/transformers''' # Matches is_xxx_available() snake_case__ : int = re.compile(R'''is\_([a-z_]*)_available()''') # Catc...
314
0
from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMSched...
124
from __future__ import annotations import math lowerCamelCase : Optional[int] = '2020.9.26' lowerCamelCase : int = 'xcodz-dot, cclaus, dhruvmanila' def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ...
124
1
"""simple docstring""" import heapq import sys import numpy as np snake_case = tuple[int, int] class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[Any] ): SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Optio...
355
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 ..utils import assert_arrow...
319
0
import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = '▁' ...
65
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { 'vocab_file': 'vocab.json', 'tokenizer_config...
65
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A : Dict = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPCon...
326
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _a ( lowerCAmelCase , unittest.TestCase): """simple docstring...
326
1
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace ...
128
def _lowerCAmelCase (_lowerCAmelCase): UpperCamelCase_ = len(_lowerCAmelCase) UpperCamelCase_ = len(matrix[0]) UpperCamelCase_ = min(_lowerCAmelCase , _lowerCAmelCase) for row in range(_lowerCAmelCase): # Check if diagonal ele...
128
1
'''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 dispatch_model, init_empty_weights fro...
360
'''simple docstring''' from __future__ import annotations from cmath import sqrt def a__ ( a__ , a__ , a__ ): """simple docstring""" if a == 0: raise ValueError("""Coefficient 'a' must not be zero.""" ) __SCREAMING_SNAKE_CASE = b * b - 4...
331
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase: List[str] = logging.get_logger(__name__) lowerCAmelCase: List[Any] ...
297
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(): import torch from ..m...
169
0
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() _A = [ "word_embeddings_layernorm.weight", "w...
137
from collections import defaultdict class lowerCamelCase : def __init__(self : Tuple , _A : Optional[int] , _A : List[str] ) -> Union[str, Any]: snake_case = total # total no of tasks (N) # DP table will have a...
137
1