code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" lowercase__ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_0000)] def _snake_case ( lowercase__ ): _lowerCamelCase : List[str] = 0 while number: # Increased Speed Slightly by checking every...
630
"""simple docstring""" from typing import Any def _snake_case ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): _validation( lowercase__ , lowercase__ , lowercase__ ,...
630
1
from __future__ import annotations from math import gcd def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase = 2 , _lowerCAmelCase = 1 , _lowerCAmelCase = 3 , ) -> int | None: """simple docstring""" if num < 2: raise ValueError("""The input value cannot b...
520
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: """simple docstring""" A : Dict = [0 for i in range(r + 1 )] # nc0 = 1 A : Dict = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. ...
520
1
"""simple docstring""" import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_sc...
82
'''simple docstring''' import math def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 0 ) -> list: """simple docstring""" _SCREAMING_SNAKE_CASE = end or len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ...
591
0
"""simple docstring""" import os from collections.abc import Iterator def _lowerCAmelCase ( UpperCAmelCase__ : str = "." ) ->Iterator[str]: for dir_path, dir_names, filenames in os.walk(UpperCAmelCase__ ): A__ : Any = [d for d in dir_names if d ...
498
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->str: if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) A__ : str = str(bin(UpperCAmelCase__ ...
498
1
# Copyright 2022 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 app...
165
import os def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : Any = len(grid[0] ) __A : Tuple = len(a ) __A : Tuple = 0 __A : Any = 0 __A : Optional[Any] = 0 # ...
239
0
'''simple docstring''' from math import factorial def _lowerCamelCase ( lowercase : List[Any] = 20 ) -> Dict: '''simple docstring''' _a = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... _a = n...
717
'''simple docstring''' import os from datetime import datetime as dt from github import Github lowerCAmelCase_ : List[Any] = [ 'good first issue', 'feature request', 'wip', ] def _lowerCamelCase ( ) -> Dict: _a = Github(os.environ["GITH...
521
0
def lowerCAmelCase__( lowercase : int , lowercase : int ) -> List[Any]: __snake_case : Any = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): __snake_case : int = n - k # Calculate C(n,k) for i ...
243
"""simple docstring""" import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor __lowercase : List[str] = logging.getLogger(__name__) __l...
142
0
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( _UpperCAmelCase ): """simple docstring""" lowercase : Optional[Any] = (CMStochasticIterativeScheduler,) lowercase : Any = 10 def lowercase...
721
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import re...
509
0
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a_ :List[Any] = '\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei an...
35
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, re...
405
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import...
510
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 snake_case_ ( a ): '''...
510
1
'''simple docstring''' import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class _lowercase ( unittest.TestCase ): def a ( self : Optional[Any] ) -> None: __snake_case ...
56
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING lowercase_ = logging.get...
695
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase_ : ...
718
# 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 SCREAMING_SNAKE_CASE_ ( __A :...
443
0
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingS...
238
"""simple docstring""" import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel lowerCamelCase__ : int = HfApi() lowerCamelCase__ : Tuple = {} # fmt: off lowerCamelCase__ : str = torch.tensor([ -0.7515, -1.6883...
238
1
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_Q...
711
'''simple docstring''' import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobe...
338
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase__ : int = { '''configuration_poolformer''': [ '''POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', ...
578
'''simple docstring''' 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 _UpperCamel...
578
1
lowerCamelCase__ : int = [0, 2, 4, 6, 8] lowerCamelCase__ : Dict = [1, 3, 5, 7, 9] def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: if remaining_l...
721
from __future__ import annotations import pandas as pd def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> list[int]: snake_case__ = [0] * no_of_processes snake_case__ = [0] * no_of_processes ...
208
0
'''simple docstring''' from __future__ import annotations lowerCAmelCase__ = list[list[int]] # assigning initial values to the grid lowerCAmelCase__ = [ [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, ...
596
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr...
596
1
'''simple docstring''' import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) def _A (...
425
'''simple docstring''' def _A ( A ) -> list: lowercase : Optional[Any] = False while is_sorted is False: # Until all the indices are traversed keep looping lowercase : List[str] = True for i in range(0 ,len(A ) - 1 ,2 ): # iterating over...
425
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: fr...
534
import requests from bsa import BeautifulSoup def lowerCamelCase__ (__lowerCamelCase = "AAPL" ): _SCREAMING_SNAKE_CASE : Dict = f"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}""" _SCREAMING_SNAKE_CASE : str = BeautifulSoup(reque...
249
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 app...
629
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ : List[str] = {"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]} try: if not is_torch_av...
629
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowercase : List[Any] =logging.get_logger(__name__) __lowercase : List[str] ={ """roberta-base""": "...
54
'''simple docstring''' 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 = [ 'wor...
350
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerat...
597
from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, require_torch_min...
597
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, ...
572
"""simple docstring""" from sklearn.metrics import matthews_corrcoef import datasets lowercase_ : Tuple = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classif...
572
1
"""simple docstring""" def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ )-> Tuple: """simple docstring""" return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_...
556
"""simple docstring""" 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 SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = 3 class...
556
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : int = { 'configuration_ele...
281
"""simple docstring""" __magic_name__ : Optional[Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' def a_ ( lowercase__ :bytes ): # Make sure the supplied data is a bytes-like object if not isinstance(lowercase__, lowercase__ ): ...
281
1
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.conver...
709
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: ...
269
0
'''simple docstring''' UpperCAmelCase_ : Any = '''Alexander Joslin''' import operator as op from .stack import Stack def _UpperCamelCase (_lowerCamelCase : List[Any] )-> int: '''simple docstring''' __snake_case = {"""*""": op.mul, """/""": op.t...
24
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {"""configuration_unispeech""": ["""UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP""", """UniSpeechCo...
299
0
from math import factorial class snake_case__: """simple docstring""" def __init__( self : List[str] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ): lowercase__ : Optional[Any] = real if isins...
81
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device ...
81
1
'''simple docstring''' import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_visi...
28
"""simple docstring""" import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( ...
177
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_ : Optional[...
500
"""simple docstring""" import math import sys def _snake_case ( UpperCAmelCase_ : int ): if number != int(UpperCAmelCase_ ): raise ValueError("""the value of input must be a natural number""" ) if number < 0: raise ValueError("""the value of in...
500
1
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 lowerCamelCase : List[str] = logging.get_logger(__name__) lowe...
587
import tensorflow as tf from ...tf_utils import shape_list class _lowerCamelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=1...
243
0
def _UpperCAmelCase ( a : List[Any] , a : Union[str, Any] ): snake_case__ = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _UpperCAmelCase ( a : str , a : Any , a...
99
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def _UpperCAmelCase ( a : List[Any] ): snake_case__ = FileLock(str(tmpdir / """foo.lock""" ) ) snake_case__ = FileLock(str(tmpdir / """foo.lock""" ) ) snake_case__ = 0....
99
1
"""simple docstring""" def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = 0 UpperCAmelCase_ = len(lowerCAmelCase__ ) for i in range(n - 1 ): for j in range(i + 1 , lowerCAmelCase__ ): if arr[i] > arr[j]: ...
82
"""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....
93
0
"""simple docstring""" def A_ ( __lowercase = 10 , __lowercase = 22 ): UpperCamelCase_ : Union[str, Any] =range(1 , __lowercase ) UpperCamelCase_ : List[Any] =range(1 , __lowercase ) return sum( 1 for power in powers for base in bases if len(str(base**power )...
395
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logg...
395
1
'''simple docstring''' import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, ...
69
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeli...
600
0
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_const...
284
import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, ...
284
1
"""simple docstring""" import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case = 1, __snake_case = 1, __snake_case = 1.0e4, __snake_case = False, __snake_case = 1.0, ) -> jnp.ndarray: """simple docstr...
19
'''simple docstring''' class lowerCAmelCase_: '''simple docstring''' def __init__( self ,__UpperCAmelCase ) -> Any: lowerCAmelCase__ : str = n lowerCAmelCase__ : Optional[Any] = [None] * self.n lowerCAmelCase__ : Tuple = 0 ...
565
0
import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) __magic_name__ = { '''iou_prediction_he...
719
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class _SCREAMING_SNAKE_CASE ( __UpperCamelCase ): _A : Any = (KDPMaDiscreteScheduler,) _A : Dict = 10 def A_...
530
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A = logging.get_logger(__name__) A ...
52
'''simple docstring''' __lowerCAmelCase ={ "meter": "m", "kilometer": "km", "megametre": "Mm", "gigametre": "Gm", "terametre": "Tm", "petametre": "Pm", "exametre": "Em", "zettametre": "Zm", "yottametre": "Ym", } # Exponent of the factor(meter) __lowerCAmelCase ={ "m"...
697
0
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import To...
59
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'...
59
1
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def _UpperCamelCase ( snake_case__ ) -> Union[str, Any]: if "model" in orig_key: __UpperCAmelCase : Tuple = orig_key.replace("model.", "" ) if "nor...
382
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, ...
322
0
def _A ( _UpperCamelCase ): if length <= 0 or not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(_UpperCamelCase )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) ...
416
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def _A ( _UpperCamelCase ): _UpperCAmelCase : Tuple = prime_factors(_UpperCamelCase ) if is_square_free(_UpperCamelCase ): return -1 if len(_UpperCamelCase ) % 2 else 1 return 0 ...
416
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase : int = logging.get_logger(__name__) lowerCAmelCase : str = { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/config.json...
372
'''simple docstring''' import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_a...
372
1
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging SCREAMING_SNAKE_CASE :...
229
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
229
1
'''simple docstring''' import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a : int = logging.get_logger(__name__) a : Any = r''' Arg...
69
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() a : List[str] = logging.get_logger(__name__) def __UpperCAmelCase ( _UpperCAm...
69
1
class _lowerCAmelCase : '''simple docstring''' def __init__( self : Optional[int] ): '''simple docstring''' _snake_case : Any = {} def UpperCamelCase_ ( self : str ): '''simple docstring''' pri...
710
def lowerCamelCase_ ( lowerCAmelCase: int )-> list: _snake_case : List[Any] = int(lowerCAmelCase ) if n_element < 1: _snake_case : int = ValueError('a should be a positive number' ) raise my_error _snake_case : Union[str, Any] ...
669
0
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 check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init...
74
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Any class lowerCAmelCase__ : def __init__( self : Any , snake_case__ : Any ): '''simple docstring''' UpperCAmelCase__ : Any = ...
438
0
def lowerCAmelCase__ ( UpperCamelCase_ : List[str] = 4_0_0_0_0_0_0 )-> Dict: A__ = [0, 1] A__ = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 A__ = 0 for j in range(len(UpperCamelCase...
714
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig _lowercase = logging.get_logger(__name__) _lowercase = "T5Config" def lowerCAmelCase__ ( Upp...
526
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available SCREAMING_SNAKE_CASE_ = {'tokenization_herbert': ['HerbertTokenizer']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() e...
582
'''simple docstring''' import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py SCREA...
582
1
'''simple docstring''' def UpperCAmelCase_ ( lowercase__ = 5_0 ): '''simple docstring''' a_ =[1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in ...
41
'''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 UpperCAmelCase : '''simple docstrin...
41
1
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class A ( UpperCAmelCase__ ): '''simple docstring''' def lowerCamelCase__ (self : List[str] , _UpperCAmelCase ...
15
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import ...
19
0
"""simple docstring""" from __future__ import annotations def _snake_case ( lowerCamelCase__ : list[int | float] , lowerCamelCase__ : int , lowerCamelCase__ : int ) -> int | float: if len(lowerCamelCase__ ) == 0: raise ValueErro...
711
"""simple docstring""" 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 lowercase__ ...
244
0
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_module...
299
"""simple docstring""" import inspect import unittest from transformers import YolosConfig 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 Co...
299
1
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def A_ ( A__ , A__ ) -> float: return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(A__ , A__ ) ) ) def A_ ( A__ , A__ ) -> list[list[list[float]...
707
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between chec...
392
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase_ = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""Mvp...
413
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCAmelCase : List[str] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: i...
202
0
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint....
525
class A_ : def __init__( self : List[Any] ): __a = {} # Mapping from char to TrieNode __a = False def _UpperCAmelCase ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : list[str] ): for word in words: self.insert(__SCREAMING_SNAKE_CA...
525
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import tr...
182
"""simple docstring""" import math def a__ ( lowerCAmelCase ) -> list[int]: UpperCAmelCase__ : Optional[int] = [] UpperCAmelCase__ : Union[str, Any] = 2 UpperCAmelCase__ : List[Any] = int(math.sqrt(lowerCAmelCase ) ) # S...
182
1
'''simple docstring''' from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCAmelCase_ ( __A : Dict ): '''simple docstring''' return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class SCREA...
692
'''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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase ...
692
1
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 A__ ( SCREAMING_SNAKE_CASE_ : dict ) -> tuple: ...
32
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _snake_case : List[str] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[str] , *lowe...
81
0
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBe...
555
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version...
555
1
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split,...
385
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class _lowercase : _a : int _a : Node | None = None _a : Node | None = N...
385
1
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils im...
716
_a = "\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" _a = [{"type": "code", "content": INSTALL_CONTENT}] _a = { "{processor_class}": "FakeProcessorC...
29
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline _a = logging.get_logger(__name__) # pylint: disable=invalid-name class ...
19
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tenso...
19
1
from __future__ import annotations import time import numpy as np UpperCAmelCase : Optional[Any] = [8, 5, 9, 7] UpperCAmelCase : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase : Any = [ [3...
77
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priori...
77
1
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets snake_case_ = datasets.logging.get_logger(__name__) snake_case_ = """\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = ...
507
'''simple docstring''' from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def __lowercase (_SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :float = 1 / sqrt(2 ) ): SCREAMING_SNAKE_CASE : List[str] ...
507
1
'''simple docstring''' import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers i...
47
'''simple docstring''' from __future__ import annotations def _a ( lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): """simple docstring""" if start is None: _snake_case : Optional[Any] = 0 if end is None: ...
47
1
'''simple docstring''' import argparse import copy def _lowerCAmelCase ( __magic_name__ : List[Any] ) -> Tuple: lowercase : Optional[int] ={} with open(__magic_name__ ) as f: for line in f: if line.split()[0] not in dict_o...
92
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def snake_case( ...
217
0
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class a__ ( unittest.TestCase ):...
355
'''simple docstring''' import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.dat...
355
1
from argparse import ArgumentParser from . import BaseTransformersCLICommand def _a ( lowerCAmelCase )-> Dict: return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class lowercase_ (SCREAMING_SNAKE_CASE__ ): ...
360
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowercase_ (SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ =(KDPMaDiscreteScheduler,) lowerCAmelCase__ =10 ...
360
1
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _lowerCamelCase ( A_ : str = "isbn/0140328726" ) -> dict: '''simple docstring''' UpperCamelCase__ : Optional[Any] =olid.strip().strip("/" ) # Remove leading/trailing whitespa...
582
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_mem...
582
1
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase : Optional[Any] = """Speech2TextFeatur...
102
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments __magic_name__ : Dict = logging.getLogger(__name__) @dataclass c...
102
1
"""simple docstring""" import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() _UpperCamelCase : str ...
710
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _UpperCamelCase : str = { "configuration_gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig", "GPTNeoOnnxConfig"],...
645
0
from collections import deque def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> List[Any]: UpperCamelCase__ : int = len(_A ) UpperCamelCase__ : int = deque() UpperCamelCase__ : Optional[Any] = [F...
228
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_avail...
328
0
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging __magic_name__ : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCam...
608
from sklearn.metrics import recall_score import datasets __magic_name__ : List[str] = '\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN ...
608
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTok...
280
from datetime import datetime as dt import os from github import Github __magic_name__ : Dict = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''feature request''', '''new model''', '''wip''', ] def lowercase__ ( ...
280
1
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 ..m...
242
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/config.json', 'google/fnet-large': 'https://huggingface.co/...
242
1
from __future__ import annotations def lowerCAmelCase_ ( __A, __A ) -> list[tuple[int, int]]: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ = position UpperCAmelCase__ = [ (y + 1, x + 2), (y - 1...
486
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_forma...
486
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel fr...
700
'''simple docstring''' import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline ...
211
0
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( """The `inpainting.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionInpaintPipeline` instead.""" )
317
import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings __lowerCamelCase = logging.getLogger(__n...
317
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import...
702
'''simple docstring''' from ... import PretrainedConfig lowercase_ : int = { '''sijunhe/nezha-cn-base''': '''https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json''', } class __UpperCamelCase (_UpperCAmelCase ): __A = NEZHA_PRETRAINED_CONFIG_ARCHIV...
653
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def UpperCamelCase_ ( A__ ): a_ = SwinConfig(image_size=1_92 ) if "base" in model_name: a_ ...
263
def lowerCAmelCase ( UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE: int = [0 for i in range(r + 1 )] # nc0 = 1 __SCREAMING_SNAKE_CASE: Dict = 1 ...
202
0
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def a ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] ): """s...
643
import requests from bsa import BeautifulSoup def a ( SCREAMING_SNAKE_CASE_ : str = "AAPL" ): """simple docstring""" UpperCamelCase : Dict = F"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}""" UpperCamelCase : Any = ...
643
1
'''simple docstring''' lowercase_ = [0, 2, 4, 6, 8] lowercase_ = [1, 3, 5, 7, 9] def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : list[int] , __lowerCamelCase : int ) ->int: ...
314
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase ( __lowerCamelCase : list , __lowerCamelCase : list ) ->list: if len(__lowerCamelCase ) != 2 or len(a[0] ) != 2 or len(__lowerCamelCase ) != 2 or len(b[0] ) !...
314
1
def _lowerCAmelCase ( _a : list ) -> int: if not grid or not grid[0]: raise TypeError("""The grid does not contain the appropriate information""" ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] lowerCAmelCase_ : ...
710
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutp...
440
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/config.json", # See all XGLM mod...
645
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Any = { "vocab_file": "vocab.json", ...
419
0
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home lowercase : List[str] = HUGGINGFACE_HUB_CACHE lowercase : Union[str, Any] = 'config.json' lowercase : List[Any] = 'diffusion_pytorch_model.bin' lowercase : ...
704
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 200) -> int: '''simple docstring''' __UpperCamelCase : Any = [1, 2, 5, 10, 20, 50, 100, 200] __UpperCamelCase : Any = [0] * (pence + 1) __UpperCamelCas...
94
0
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from tr...
81
def lowercase_ ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if num < 0: return False snake_case__ : int =num snake_case__ : int =0 while num > 0: snake_case__ : int =rev_num * 10 + (num % 10) num //= 10 return num_copy ==...
381
0
import string def SCREAMING_SNAKE_CASE ( snake_case_ : str ): snake_case__ : Union[str, Any] = "" for i in sequence: snake_case__ : int = ord(snake_case_ ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 1...
25
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 ...
25
1
from timeit import timeit def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> int: if number < 0: raise ValueError('the value of input must not be negative' ) SCREAMING_SNAKE_CASE_ : Tuple = 0 while number: number &= number - 1 result += 1 return result def _...
345
from timeit import timeit def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> int: if number < 0: raise ValueError('the value of input must not be negative' ) SCREAMING_SNAKE_CASE_ : Tuple = 0 while number: number &= number - 1 result += 1 return result def _...
345
1
"""simple docstring""" _lowercase : Union[str, Any] = frozenset( [ "prompt", "height", "width", "guidance_scale", "negative_prompt", "prompt_embeds", "negative_prompt_embeds", "cross_attention_kwargs", ] ) _lowercase : T...
625
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax imp...
625
1
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if length <= 0 or not isinstance(snake_case_ ,snake_case_ ): raise ValueError("""Length must be a positive integer.""" ) return [n * (2 * n - 1) for n in range(snake_case_ ...
499
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, ...
499
1
from __future__ import annotations def _snake_case ( __snake_case ) -> Optional[int]: # This function is recursive '''simple docstring''' UpperCAmelCase_ : Tuple = len(__lowerCAmelCase ) # If the array contains only one element, we return it (...
718
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and ...
455
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a__ : '''simple docstring''' def __init__( self , lowerCamelCase_=...
90
'''simple docstring''' import re def _snake_case ( A ) -> bool: lowerCAmelCase__ = re.compile(R'''^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$''' ) if match := re.search(A , A ): return match.string == phone return False if _...
90
1
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class _A ( lowerCAmelCase ): snake_case__ : Optional[int] = 'EncodecFeatureExtractor' snake_ca...
197
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common im...
197
1
"""simple docstring""" import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup lowerCamelCase__ : Any = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safa...
698
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ : int = logging.get_logger(__name__) lowerCamelCase__ : str = { "studio-ousia/luke-base": "https://huggingface.co/studio-ousia/luke-base/resolve/main...
698
1
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( Autoencode...
449
'''simple docstring''' def UpperCAmelCase ( UpperCAmelCase__ : int = 10_00): lowerCamelCase : Optional[Any] = 2**power lowerCamelCase : str = str(UpperCAmelCase__) lowerCamelCase : Union[str, Any] = list(UpperCAmelCase__) ...
449
1
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class __UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple do...
255
"""simple docstring""" import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_...
695
0
def snake_case_ ( lowercase__ : list[int] ): '''simple docstring''' _lowerCAmelCase =[] if len(lowercase__ ) == 1: return [nums.copy()] for _ in range(len(lowercase__ ) ): _lowerCAmelCase =nums.pop(0 ) _lowerCAmelCase ...
149
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 accelerate.test_utils import Regr...
149
1
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository ch...
64
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class _lowerCamelCase ( unittest.TestCase ): def UpperCamelCase_ ( self ) -> List[Any]: SCREAMING_SNAKE_CASE__: Tuple= get_activation('''swish''' ) self.assertIsI...
64
1
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils ...
721
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, ...
447
0