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
def lowerCamelCase__ ( _a = 4000000): SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(_a) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[str] = b, a + b ...
25
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 _UpperCamelCase ( unittest.TestCase ): '''simpl...
25
1
from collections import defaultdict def __UpperCamelCase ( A , A ): UpperCamelCase__ = first_str.lower().strip() UpperCamelCase__ = second_str.lower().strip() # Remove whitespace UpperCamelCase__ = first_str.replace(...
469
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __magic_name__ =logging.get_logger(__name__) __magic_name__ =...
469
1
'''simple docstring''' from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_availa...
467
'''simple docstring''' import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCAmelCase ( _snake_case ...
467
1
"""simple docstring""" from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, require_torch_neuro...
668
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import ...
668
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): ...
73
'''simple docstring''' import csv import tweepy # Twitter API credentials __lowerCamelCase = '''''' __lowerCamelCase = '''''' __lowerCamelCase = '''''' __lowerCamelCase = '''''' def UpperCAmelCase__ ( UpperCAmelCase__ ) -> None: # ...
288
0
import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def __SCREAMI...
702
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a ni...
311
0
"""simple docstring""" import re def __A ( a_ :str) -> str: if len(re.findall('''[ATCG]''' , a_)) != len(a_): raise ValueError('''Invalid Strand''') return dna.translate(dna.maketrans('''ATCG''' , '''TAGC''')) if __name__ == "__main__"...
52
'''simple docstring''' a__ : Optional[Any] = '''Alexander Joslin''' import operator as op from .stack import Stack def __lowerCamelCase ( UpperCAmelCase_ ) ->int: snake_case__ = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} ...
368
0
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging l...
549
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase = False ): if not isinstance(_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : str = F"Expected string as input, found {type(_UpperCamelCase )}" raise ValueError(_UpperCamelCase ) if not i...
549
1
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets A__ : str = datasets.logging.get_logger(__name__) A__ : Dict = '\\n@InProceedings{m...
153
"""simple docstring""" import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_P...
153
1
from __future__ import annotations import typing from collections import Counter def snake_case__ ( __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: UpperCAmelCase_ = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(_lowerCAmelCase , max_perim...
700
import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def snake_case__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ...
23
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class snake_case_ ( metaclass=lowerCamelCase_ ): """simple docstring""" A_ = ['''torch'''] def __init__( self , *lowerCamelCase_ , **lowerCamelCase_) -> ...
34
"""simple docstring""" import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def __snake_case ( ): """simple docstring""" raise RuntimeError('''CUDA out o...
34
1
"""simple docstring""" 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...
721
"""simple docstring""" import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCas...
545
0
def _SCREAMING_SNAKE_CASE ( lowercase : int , lowercase : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) lowerCamelCase_ = str(bin(lowercase ) )[2:] # rem...
70
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer __lowercase = logging.get_logger(__name__) __lowercas...
203
0
'''simple docstring''' def UpperCAmelCase ( lowercase__ : int = 600851475143 ): '''simple docstring''' try: a__ = int(lowercase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: ...
705
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...
412
0
import numpy as np from transformers import Pipeline def lowerCAmelCase__(__snake_case ) -> Optional[Any]: '''simple docstring''' lowerCamelCase__ = np.max(__snake_case ,axis=-1 ,keepdims=__snake_case ) lowerCamelCase__ = np.exp(outputs - ...
481
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", "MobileBertConfig",...
481
1
'''simple docstring''' import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_ten...
424
'''simple docstring''' UpperCAmelCase_ : Union[str, Any] = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .feat...
424
1
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureE...
613
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a : Optional[int] = logging.get_logger(__name__) a : Optional[Any] ...
613
1
'''simple docstring''' 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_CHEC...
701
'''simple docstring''' from __future__ import annotations def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): if b == 0: return (1, 0) ((a__) , (a__)) : int = extended_euclid(lowerCAmelCase__ , a % b ) a__ : Opti...
340
0
"""simple docstring""" def UpperCamelCase ( _lowerCAmelCase : list, _lowerCAmelCase : list ) -> float: _validate_point(_UpperCAmelCase ) _validate_point(_UpperCAmelCase ) if len(_UpperCAmelCase ) != len(_UpperCAmelCase ): raise ValueError("""Both points...
238
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class lowerCamelCase_ (snake_case__ ): '''simple docstring''' __UpperCamelCase: str = "M-CLIP" def __init__( self : Union[str, Any] , A : ...
244
0
import math import sys import cva import numpy as np def A__ ( _a : np.ndarray , _a : float ): '''simple docstring''' snake_case__ : Optional[Any] =math.sqrt(_a ) snake_case__ : Dict =1 / (sigma * math.sqrt(2 * math.pi )) return ...
448
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": __lowerCamelCase : List[str] = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", ...
448
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=_a ) class __a( _a ): """simple docstring""" lowerCAmelCase = field(default='''image-classifi...
30
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision fr...
299
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/LICENSE...
295
"""simple docstring""" import collections import os import re from pathlib import Path lowercase_ : Union[str, Any] = '''src/transformers''' # Matches is_xxx_available() lowercase_ : str = re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import...
295
1
import math class __lowercase : def UpperCamelCase__ ( self , A_ , A_ ) ->int: '''simple docstring''' __lowerCAmelCase : Any = 0.0 __lowerCAmelCase : List[str] = 0.0 for i in range(len(A_ ) ): da += math.pow((sample[i...
492
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificat...
492
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = { """configuration_bigbird_pegasus""": [ """BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BigBirdPegasusConfig""", """BigBirdPegasusOnnxConfig""",...
689
import os import sys import unittest __a = 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 ...
689
1
"""simple docstring""" from typing import Dict, Optional import numpy as np import datasets A_ : Optional[int] ='\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (tw...
650
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_: int = { 'configuration_lxmert': ['LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LxmertC...
648
0
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import nu...
703
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 100_0000 ) -> int: _a = set(range(3 , lowercase , 2 ) ) primes.add(2 ) for p in range(3 , lowercase , 2 ): if p not in primes: continue...
521
0
"""simple docstring""" import random class lowerCAmelCase_ : '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : str ) -> tuple[list[int], list[int]]: A = [ord(A_ ) for i in text] A = [] A = [] for i in p...
91
"""simple docstring""" 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.distribu...
91
1
# 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 SCREAMING_SNAKE_CASE__ : List[str] = TypeVar("""T""") class lowerCamelCase_ ( Generic[T] ...
180
import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def __lowercase ( ): """simple ...
180
1
"""simple docstring""" import argparse import collections import json import os import re import string import sys import numpy as np UpperCAmelCase = re.compile(r"""\b(a|an|the)\b""", re.UNICODE) UpperCAmelCase = None def _snake_case ( ): """simple docs...
88
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: ...
23
0
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _snake_case : List[str] = {"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]} try: if not is...
493
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowerCAmelCase ( __UpperCAmelCase ): def __init__( self , UpperCamelCase , UpperCamelCase , UpperCamelCase ...
493
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = {'''configuration_mbart''': ['''MBART_PRETRAINED_...
84
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase ...
84
1
def UpperCamelCase__ ( UpperCAmelCase = 1000 ) -> int: """simple docstring""" _a : Optional[int] = 2**power _a : Union[str, Any] = 0 while n: _a , _a : Optional[int] = r + n % 10, n // 10 re...
307
import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def UpperCamelCase__ ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Tuple: ...
307
1
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def lowerCAmelCase (__A): """simple docstring""" ...
11
"""simple docstring""" from __future__ import annotations import time A : List[str] = list[tuple[int, int]] A : Tuple = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, ...
516
0
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva UpperCamelCase : Dict = '' UpperCamelCase : Any = '' UpperCamelCase : Optional[Any] = '' UpperCamelCase : Optional[Any] = 1 # (0 is vertica...
9
'''simple docstring''' def A__ ( ): return [ a * b * (1000 - a - b) for a in range(1 , 999 ) for b in range(__lowerCAmelCase , 999 ) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(F...
9
1
import math def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> float: 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 > 360: rais...
89
"""simple docstring""" __snake_case : str = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip...
571
0
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class __a( _a ): """simple docstri...
710
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavavec...
300
0
'''simple docstring''' def a__ ( _SCREAMING_SNAKE_CASE : int | float | str ) -> tuple[int, int]: """simple docstring""" try: UpperCAmelCase_ : int = float(_SCREAMING_SNAKE_CASE ) except ValueError: raise ValueError("Please enter a valid numbe...
71
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __a ( unitte...
228
0
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as comp...
719
from ..utils import DummyObject, requires_backends class A__ ( metaclass=__snake_case ): _UpperCAmelCase :Tuple = ['note_seq'] def __init__( self , *A_ , **A_ ): '''simple docstring''' requires_backends(self , ["note_seq"] ...
38
0
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets a__ = """\ @inproceedings{popovic-2015-chrf, title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\", author = \"Popovi{\'c}, Maja\", booktitle = \"Proceedings of the Tenth Work...
654
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _lowerCAmelCase ( lowercase_ ): """simple do...
654
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from tr...
704
"""simple docstring""" import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def __lowercase (...
363
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase ...
453
"""simple docstring""" import argparse import gc import json import os 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 acce...
453
1
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def UpperCAmelCase ( A : float , A : float , A : bool = False ): '''simple docstring''' ...
715
"""simple docstring""" 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 fr...
24
0
"""simple docstring""" from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline __UpperCAmelCase = logging.get_logger(__name__) clas...
642
"""simple docstring""" from sklearn.metrics import matthews_corrcoef import datasets __UpperCAmelCase = ''' 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 classifications. It ...
642
1
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class UpperCamelCase__ : '''simple docstring''' __a : Tuple = None def A__ ( self ) ->Any: UpperCAmelCase__ :List[str] = ...
433
from math import isqrt def A ( SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCAmelCase__ :str = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , SCREAMING_SNAKE_CASE , SCREAMING_...
433
1
import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def ...
63
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib...
63
1
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import p...
716
def __UpperCAmelCase ( snake_case_ : int = 6_0_0_8_5_1_4_7_5_1_4_3 ): '''simple docstring''' try: UpperCAmelCase: Optional[int] = int(snake_case_ ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) i...
166
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A : int = {"""configuration_glpn""": ["""GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GLPNConfig"""]} try: if not is_vision_available(): raise OptionalDepe...
100
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects impo...
100
1
'''simple docstring''' from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cach...
98
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='''session''' ) def...
98
1
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_comm...
90
'''simple docstring''' from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concaten...
229
0
'''simple docstring''' from ...processing_utils import ProcessorMixin class _snake_case ( a_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = ['''image_processor''', '''feature_extractor'''] SCREAMING_SNAKE_CASE : Optional[int] = '''TvltImageProcessor''' SCREAMING_SNAKE...
514
'''simple docstring''' import torch def snake_case ( ) -> List[str]: """simple docstring""" if torch.cuda.is_available(): lowerCAmelCase = torch.cuda.device_count() else: lowerCAmelCase = 0 print(F'Successfully ran on {num_gpus} GPUs' ) if __...
514
1
import argparse import importlib from pathlib import Path # Test all the extensions added in the setup a : Tuple = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.c...
556
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils impo...
510
0
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import T...
138
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE : Optional[Any] = { "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "Cl...
138
1
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def A ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Tuple: A__ = s.rsplit(__UpperCamelCase , __UpperCamelCase ...
9
from __future__ import annotations from fractions import Fraction def A ( __UpperCamelCase , __UpperCamelCase ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def A ( __UpperCamelCase ) -> list[str]:...
9
1
from __future__ import annotations def __UpperCamelCase ( A , A ): UpperCamelCase__ = get_failure_array(A ) # 2) Step through text searching for pattern UpperCamelCase__ , UpperCamelCase__ = 0, 0 # index into text, pat...
469
def __UpperCamelCase ( A = 600851475143 ): try: UpperCamelCase__ = int(A ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be ...
469
1
from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCAmelCase__ ( snake_case ): """simple docstring""" @staticmethod @abstractmethod def _UpperCAmelCase ( __lowerCAmelCase: ArgumentParser ) -> Optional[Any]: '''simple docs...
221
def __lowerCAmelCase ( A_ : str ) -> str: __UpperCAmelCase = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def __lowerCAmelCase ( A_ : str ) -> dict[str, str]: __UpperCAmelCase ...
221
1
from __future__ import annotations def lowerCamelCase_ ( A : float , A : float , A : float , ): """simple docstring""" if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) el...
413
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 _snak...
413
1
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea im...
233
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from t...
38
0
"""simple docstring""" def _snake_case ( UpperCAmelCase_ : int = 100_0000 ): A__ = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , UpperCAmelCase_ ...
702
"""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
0
import re def _UpperCamelCase (a__ :str ): """simple docstring""" UpperCamelCase__ = re.compile(r"""^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$""" ) if match := re.search(a__ , a__ ): return match.string == phone return Fals...
619
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, r...
619
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class lowercase__ ( unittest.TestCase...
705
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A = logging.getLogger(__name__) @dataclass class lowercase__ ( __SCREAMING_SNAKE_CASE ): A__= field( ...
277
0
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, Tens...
7
'''simple docstring''' def _UpperCamelCase (_lowerCamelCase : Optional[Any] )-> Dict: '''simple docstring''' __snake_case = [] __snake_case = [] __snake_case = { '''^''': 3, '''*''': 2, '''/''': 2, ...
24
0
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str , lowerCAmelCase: str ) -> int: if len(lowerCAmelCase ) != len(lowerCAmelCase ): raise ValueError("String lengths must match!" ) _UpperCAmelCase : List[Any] = 0 for chara, chara in zip(lowerCAmelCase , ...
467
import logging import os from .state import PartialState class a ( logging.LoggerAdapter ): @staticmethod def _UpperCAmelCase ( A_ ): '''simple docstring''' _UpperCAmelCase : Tuple = PartialState() return not main_process_only ...
467
1
"""simple docstring""" import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from...
575
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from a...
575
1
'''simple docstring''' import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : Optional[int] = { 'vocab_fil...
159
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar lowercase : Union[str, Any] = TypeVar('T') class _lowerCAmelCase ( Generic[T] ): """simple docstring""" def __init__( self ...
159
1
import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_i...
201
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCAmelCase = { 'configuration_bridgetower': [ 'BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BridgeTowerConfig', 'BridgeTowerTextCo...
201
1
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ : Any = logging.get_logger(__name__) snake_case_ : Union[str, Any] = { 'ka...
718
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestC...
166
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow...
17
'''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/LICENSE-2...
98
0
'''simple docstring''' def A__ ( _a : int , _a : int ): '''simple docstring''' if number < 0 or shift_amount < 0: raise ValueError("""both inputs must be positive integers""" ) snake_case__ : List[Any] =str(bin(__A ) ) binary_number += "0" * shif...
708
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIP...
448
0
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, A...
506
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, ...
222
0
from __future__ import annotations def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' A_ = [] create_all_state(1 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , [] , SCREAMING_SNAKE...
700
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer __lowercase = logging.get_logger(__name__) __lowercase = {...
563
0
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging A_: List[Any] = logging.get_logger(__name__) def __lowerCAmelCase ( _A ): """simple docstring""" _lowercase = ...
398
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ): @register_to_config def __init__( self :Tuple , *, lowercase :i...
201
0
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm imp...
60
from __future__ import annotations from random import random from typing import Generic, TypeVar __snake_case :Any = TypeVar('''KT''') __snake_case :List[str] = TypeVar('''VT''') class _A ( Generic[KT, VT] ): def __init__( self : Dict , __SCREAMING_SNAKE_CASE : KT | ...
60
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, ...
61
# 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 by app...
454
0
def _lowercase ( lowercase__ ): __lowerCAmelCase : str = len(lowercase__ ) for i in range(1 , lowercase__ ): __lowerCAmelCase : Optional[Any] = collection[i] __lowerCAmelCase : Any = 0 __lowerCAmelCase :...
583
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _UpperCamelCase = { "configuration_gpt_neox_japanese": ["GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXJapaneseConfig"], "tokenization_gpt_neox_j...
583
1
lowerCAmelCase = [0, 2, 4, 6, 8] lowerCAmelCase = [1, 3, 5, 7, 9] def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" if remaining_length == 0: if digits[0] == 0 or digits[-1] ...
43
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> int: if not isinstance(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ): raise TypeError("Input value must be an 'int' type" ) lowercase__ : str = 0 while number: ...
397
0
'''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...
159
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffuse...
159
1
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_g...
539
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG...
539
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase = logging.get_logger(__name__) lowercase = { "google/pegasus-large": "https://huggingface.co/google/pegasus-large/resolve/main/config.json", # See all PEGASUS models at https://h...
718
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYP...
591
0
import math class lowerCAmelCase_ : def __init__( self : Tuple , _A : int=0 ): # a graph with Node 0,1,...,N-1 _UpperCamelCase = n _UpperCamelCase = [ [math.inf for j in range(0 , _A )] for i in range(0 , _A...
10
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging f...
278
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : Dict = logging.get_logger(__name__) __lowerCamelCase : Tuple = { '''microsoft/unispeech-sat-base-100h-libri-ft''': ( '''https://h...
316
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __lowerCamelCase : Dict = HUGGINGFACE_HUB_CACHE __lowerCamelCase : Union[str, Any] = '''config.json''' __lowerCamelCase : Tuple = '''diffusion_pytorch_model.bin''' __l...
316
1
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ): a ...
445
'''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 UpperCamelCase__ : Optional[Any] = logging.getLogger(__name__) Uppe...
614
0
from __future__ import annotations from collections.abc import MutableSequence class __magic_name__ : """simple docstring""" def __init__( self , a__ , a__ ): if len(a__ ) != degree + 1: raise ValueError( '''The number of coefficients should be equal to the degree + 1....
297
import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_fla...
297
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_availabl...
19
'''simple docstring''' from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case_ = datasets.load_iris() snake_case_ = np.array(data["""data"""]) snake_case_ = np.array(data["""target"""]) snake_case_ = ...
507
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_:Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_:Optional[int] = { """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/c...
718
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) fr...
520
0
"""simple docstring""" def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def A_ ( ): '''simple docstring''' print("""Truth Table of NOR Gate:""" ) print("""| Inp...
499
"""simple docstring""" def A_ ( snake_case_ : int = 1_0_0_0_0_0_0 ): '''simple docstring''' UpperCamelCase : List[Any] = [i - 1 for i in range(limit + 1 )] for i in range(2 ,limit + 1 ): if phi[i] == i - 1: for j in range(...
499
1
"""simple docstring""" import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ....
165
"""simple docstring""" def _lowerCAmelCase(a : int ) -> bool: if p < 2: raise ValueError('''p should not be less than 2!''' ) elif p == 2: return True _SCREAMING_SNAKE_CASE =4 _SCREAMING_SNAKE_CASE =(1 << p) - 1 for _ in range(p - 2 ): _SCREAMING_S...
165
1
import numpy as np def UpperCamelCase ( __lowerCamelCase : np.ndarray ): return 1 / (1 + np.exp(-vector )) def UpperCamelCase ( __lowerCamelCase : np.ndarray ): return vector * sigmoid(__lowerCamelCase ) if __name__ == "__main__"...
204
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...
204
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusion...
712
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .at...
228
0
import operator def A ( _lowerCamelCase , _lowerCamelCase = False , _lowerCamelCase = None ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = operator.lt if reverse else operator.gt _lowerCAmelCase : int = ...
500
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging _snake_case = loggi...
500
1
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mo...
138
import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Any , _SCREA...
138
1
import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class __magic_na...
628
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCA...
628
1
import numpy as np def A__ ( __lowerCamelCase ): return 1 / (1 + np.exp(-vector )) def A__ ( __lowerCamelCase ): return vector * sigmoid(1.7_02 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
597
def A__ ( __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = len(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in ra...
597
1
"""simple docstring""" from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from...
589
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...
351
0
from __future__ import annotations def __UpperCamelCase ( a, a = None) ->List[str]: lowerCamelCase__ = word_bank or [] # create a table lowerCamelCase__ = len(snake_case_) + 1 lowerCamelCase__ = [] for _ in range(snake_case_): ...
710
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tok...
360
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : Union[str, Any] = logging.get_logger(__name__) lowercase__ : Dict = { 'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.j...
98
'''simple docstring''' 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_ = { """distilbert-base...
314
0
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) _snake_case = logging.getLogger(__name__...
715
"""simple docstring""" import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attenti...
491
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase : Any = { '''configuration_blip_2''': [ '''BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Blip2Config''', ...
4
import math def UpperCamelCase ( _A, _A ): """simple docstring""" __magic_name__ : Optional[int] = len(_A ) __magic_name__ : Tuple = int(math.floor(math.sqrt(_A ) ) ) __magic_name__ : Optional[int] = 0 w...
324
0
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] __UpperCAmelCase : ...
715
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerM...
319
0
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trus...
41
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): ...
483
0
"""simple docstring""" from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar __A = TypeVar('''T''') class _snake_case ( Generic[T] ): def __init__( self : Union[str, Any] , UpperCAmelCase : Any ...
719
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_ava...
366
0