code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
# 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 SchedulerMixin class A__ ...
52
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils i...
340
0
def SCREAMING_SNAKE_CASE_ ( __A : int ) -> int: """simple docstring""" if not isinstance(__A , __A ): raise ValueError('Input must be an integer' ) if input_num <= 0: raise ValueError('Input must be positive' ) ...
120
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Any = { 'configuration_mobilebert': [ 'MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_...
120
1
"""simple docstring""" import functools def lowerCamelCase__ ( _lowerCamelCase : list[int] , _lowerCamelCase : list[int] ) -> int: # Validation if not isinstance(_lowerCamelCase , _lowerCamelCase ) or not all(isinstance(_lowe...
183
"""simple docstring""" from math import pow, sqrt def lowerCamelCase__ ( *_lowerCamelCase : float ) -> bool: lowerCamelCase_ = len(_lowerCamelCase ) > 0 and all(value > 0.0 for value in values ) return result def ...
183
1
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, r...
308
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) _lowerCAmelCase : ...
308
1
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSear...
33
'''simple docstring''' from heapq import heappop, heappush import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) -> tuple[float | int, list[tuple[int, int]]]: lowerCamel...
41
0
'''simple docstring''' import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_availa...
363
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
294
0
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 lowerCamelCase : Union[str, Any] = logging.getLogger(__name__) lowerCamelCase ...
124
def SCREAMING_SNAKE_CASE__ ( ) -> int: return [ a * b * (1000 - a - b) for a in range(1 ,999 ) for b in range(lowercase ,999 ) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(f"""{solution() = }""")
124
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING a : Dict ...
359
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transf...
150
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @r...
292
"""simple docstring""" def A__ ( UpperCamelCase , UpperCamelCase = False ): if not isinstance(UpperCamelCase , UpperCamelCase ): A = F"Expected string as input, found {type(UpperCamelCase )}" raise ValueError(UpperCamelCase ) ...
292
1
"""simple docstring""" import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_x...
359
"""simple docstring""" def __A ( a_ :int) -> Union[str, Any]: __a : int = [] __a : Dict = [] __a : str = { '''^''': 3, '''*''': 2, '''/''': 2, '''%''': 2, '''+''': 1, ...
188
0
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : list[list] ) ->list[list]: _SCREAMING_SNAKE_CASE = current_set.copy() for row_index, row in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = row[0] for column_index, column in en...
58
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowercase_ = { """<""": operator.lt, """<=""": operator.le, """==""": operator.eq, """!=""": operator.ne, """>=""": operator.ge, """>""": ...
58
1
'''simple docstring''' from __future__ import annotations def lowerCamelCase (_SCREAMING_SNAKE_CASE : int | float | str , _SCREAMING_SNAKE_CASE : int | float | str ): if nth_term == "": return [""] __a : str = int(_SCREAMING_SNAKE_CASE ...
294
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...m...
294
1
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake lowerCamelCase__ = numpy.array([0, 0]) lowerCamelCase__ = numpy.array([0.5, 0.866_0254]) lowerCamelCase__ = numpy.array([1, 0]) lowerCamelCase__ = [VECTOR_1,...
302
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer,...
303
0
"""simple docstring""" import numpy as np lowercase__ : str = [ ['''a''', '''b''', '''c''', '''d''', '''e'''], ['''f''', '''g''', '''h''', '''i''', '''k'''], ['''l''', '''m''', '''n''', '''o''', '''p'''], ['''q''', '''r''', '''s''', '''t''', '''u'''], ['''v''', '''w''', '''x'''...
155
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase__ : str = { '''configuration_resnet''': ['''RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP...
155
1
'''simple docstring''' import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from...
70
"""simple docstring""" import re def _lowercase ( __snake_case ) -> str: if len(re.findall("[ATCG]" ,__snake_case ) ) != len(__snake_case ): raise ValueError("Invalid Strand" ) return dna.translate(dna.maketrans("ATCG" ,"TAGC" ) ) if __name__ == "_...
269
0
"""simple docstring""" import unittest from transformers import MraConfig, 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, floats_tensor, ids_tensor, random_att...
23
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _a = logging.get_logger(__name__) class...
23
1
'''simple docstring''' import os from collections import deque import torch from torch.utils.data import Dataset class __snake_case ( _SCREAMING_SNAKE_CASE): """simple docstring""" def __init__( self : Optional[Any] , lowerCamel...
120
'''simple docstring''' def UpperCamelCase_ ( A__ : str , A__ : list[str] ): '''simple docstring''' lowerCAmelCase_ : Dict = """""" for word_or_phrase in separated: if not isinstance(A__ , A__ ): raise Exception("...
120
1
from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class __A ( lowerCAmelCase ): def __init__( self : ...
323
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, ) __A : List[Any] = { '''configuration_xlm_roberta'''...
323
1
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, ...
308
def snake_case( __magic_name__ = 50 ) -> int: '''simple docstring''' lowercase : Union[str, Any] = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in rang...
308
1
"""simple docstring""" def snake_case__ ( __lowerCamelCase : int ): """simple docstring""" if n == 1 or not isinstance(__lowerCamelCase , __lowerCamelCase ): return 0 elif n == 2: return 1 else: lowerCamelCase__ : Optional[Any] =[0, 1] ...
272
"""simple docstring""" import math import flax.linen as nn import jax.numpy as jnp def snake_case__ ( __lowerCamelCase : jnp.ndarray , __lowerCamelCase : int , __lowerCamelCase : float = 1 , __lowerCamelCase : float = 1 , __lowerCamelCase :...
272
1
from collections.abc import Generator from math import sin def __snake_case ( _UpperCAmelCase ): if len(_UpperCAmelCase ) != 32: raise ValueError('''Input must be of length 32''' ) __a = b'''''' for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i ...
49
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ...
294
0
A_ :Union[str, Any] = [ '''DownloadConfig''', '''DownloadManager''', '''DownloadMode''', '''StreamingDownloadManager''', ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import St...
360
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging A_ :Union[str, Any] = logging.get_logger(__name__) A_ :Tuple = { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/config.json''', '''x...
245
0
def __lowerCamelCase ( UpperCAmelCase_ : int = 50 ): """simple docstring""" a :str = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_s...
94
"""simple docstring""" from __future__ import annotations from cmath import sqrt def lowerCAmelCase__ ( _UpperCamelCase : int , _UpperCamelCase : int , _UpperCamelCase : int ) -> tuple[complex, complex]: """simple docstring""" if a ==...
150
0
__lowerCamelCase : List[str] = {str(digit): digit**5 for digit in range(10)} def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(__UpperCamelCase ) )...
204
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sent...
204
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=__UpperCAmelCase ) class _A ( __UpperCAmelCase ): UpperCamelCase__ : str = field(default='...
49
from math import factorial def UpperCAmelCase__ ( _A : int = 1_00 ): '''simple docstring''' return sum(int(_A ) for x in str(factorial(_A ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
188
0
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase__ ) class a__( lowerCamelCase__ ): # `task` is not a ClassVar since ...
360
'''simple docstring''' import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = CTRLTokeni...
96
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, ) _snake_case = { 'configuration_whis...
294
"""simple docstring""" import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_s...
294
1
'''simple docstring''' import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets _lowercase : List[str] = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation ...
91
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int = logging.get_logger(__name__) _lowercase : Optional[Any] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json...
91
1
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available f...
155
"""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...
155
1
"""simple docstring""" def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = [] _snake_case : List[str] = 1 while len(snake_case__ ) < 1e6: constant.append(str(snake_case__ ) ) i += 1 _snake_case : List[Any] ...
371
"""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 .embe...
132
0
'''simple docstring''' import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from .....
23
'''simple docstring''' import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test,...
23
1
"""simple docstring""" lowerCamelCase__ = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import ...
182
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""", } clas...
182
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class UpperCamelCase__ ( lowercase_ ): ...
323
'''simple docstring''' from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class UpperCamelCase__ ( lowercase_ ): """simple docst...
323
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING A__ : Optional[Any] = logging.get_logger(...
209
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( Autoe...
209
1
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase = { '''susnato/ernie-m-base_pytorch''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json''', '''susnato/ernie-m-large_py...
272
'''simple docstring''' def snake_case__ ( _A: int , _A: int ) -> int: '''simple docstring''' while a != 0: lowerCAmelCase , lowerCAmelCase = b % a, a return b def snake_case__ ( _A: int , _A: int ) -> int: '''simple do...
272
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtraction...
226
"""simple docstring""" from math import ceil, sqrt def lowercase ( A_ = 1_000_000 )-> int: '''simple docstring''' a : Tuple = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a : ...
226
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image...
148
def __lowercase ( _A ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("""Program to check whether a number is a Perfect number or not...""") UpperCAmelCase__ : Optional[int] = int(input("""Ente...
245
0
"""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 im...
32
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __lowerCAmelCa...
32
1
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _SCREAMING_SNAKE_CASE ( ...
204
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Optional[Any] = { "configuration_whisper": ["WHISPER_PR...
204
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, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ....
119
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_...
119
1
"""simple docstring""" import math def __a ( _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: return math.sqrt(lowercase__ ) * math.sqrt(lowercase__ ) == num def __a ( _SCREAMING_SNAKE_CASE ) ->int: a__: Optional[int] = 0 a__: List[Any] = n while left <=...
290
"""simple docstring""" import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextI...
96
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = { """configuration_time_series_transformer""": [ """TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimeSer...
353
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, ...
253
0
"""simple docstring""" from __future__ import annotations def _A (__a , __a ) -> list[list[int]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : list[list[int]] = [] create_all_state(1 , __a , __a , [] , __a ) r...
91
"""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_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ ...
91
1
from __future__ import annotations import math def UpperCAmelCase_ ( __UpperCAmelCase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even...
210
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod @abstractmethod def lowerCAmelCase_ ( _lowerCAmelCase : ArgumentParser ): raise NotImplementedError() ...
210
1
"""simple docstring""" def __a ( __lowerCamelCase, __lowerCamelCase ): return x if y == 0 else greatest_common_divisor(__lowerCAmelCase, x % y ) def __a ( __lowerCamelCase, __lowerCamelCase ): return (x * y) // greatest_common_divisor(__lowerCAmelCase, __lowerCAmelCase ) de...
61
"""simple docstring""" import unittest from typing import Dict, List, Optional, Union 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 ImageProcessingSavingTes...
132
0
"""simple docstring""" from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES,...
369
"""simple docstring""" def _UpperCAmelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple ) -> Union[str, Any]: # Return True if there is node that has not iterated. _snake_case = [False]...
40
0
import math def A ( _lowercase ): return math.sqrt(_lowercase ) * math.sqrt(_lowercase ) == num def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Tuple = n while left <= right: ...
182
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def A ( _lowercase ): if "model" in orig_key: SCREAMING_SNAKE_CASE : int = orig_key.replace('''model.''' , '''''' ) if "norm1" in orig_key: SCREAMING...
182
1
"""simple docstring""" from statistics import mean, stdev def snake_case (__lowercase , __lowercase = 3 ) -> list: '''simple docstring''' _snake_case : Optional[Any] = min(__lowercase ) _snake_case : List[Any] = max(__lowercase ) # no...
358
def snake_case (__lowercase ) -> list[int]: '''simple docstring''' if num <= 0: raise ValueError("Input must be a positive integer" ) _snake_case : Any = [True] * (num + 1) _snake_case : str = 2 while p * p <= num: i...
284
0
from __future__ import annotations def lowerCAmelCase__(__snake_case ,__snake_case ) -> Tuple: '''simple docstring''' print(F'Vertex\tShortest Distance from vertex {src}' ) for i, d in enumerate(__snake_case ): print(F'{i}\t\t{d}' ) def lowerCAmel...
209
from __future__ import annotations from random import random class __A : '''simple docstring''' def __init__( self , __lowerCAmelCase = None ): '''simple docstring''' lowerCamelCase__ = value lowerCamelCase__ = random() lowerCa...
209
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : str = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise Option...
57
"""simple docstring""" import json import os import unittest from typing import Tuple from transformers import WavaVecaPhonemeCTCTokenizer from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonem...
57
1
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( __UpperCamelCase ): ...
226
import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer ...
226
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ...
361
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_t...
141
0
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch UpperCAm...
32
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @requ...
32
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : int = logging.get_logger(__name__) _snake_case : Tuple = { 'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/co...
179
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _snake_case : int = {'configuration_yolos': ['YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'YolosConfig', 'YolosOnnxConfig...
179
1
def UpperCamelCase ( snake_case__ : Any , snake_case__ : Union[str, Any] , snake_case__ : List[str] , snake_case__ : Optional[Any] , snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] ) -> Op...
119
import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import loggi...
119
1
import os import re import shutil import sys import tempfile import unittest import black UpperCamelCase__ =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_copies # noqa: E402 # This...
354
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , *__lowerCamelCase ...
325
0
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_token...
101
lowerCAmelCase : str = '0.21.0' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches...
253
0
"""simple docstring""" from functools import lru_cache def lowerCAmelCase_( lowercase_ : int ) -> set: _lowerCamelCase = 2 _lowerCamelCase = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.ad...
73
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE : Dict = { '''configuration_blenderbot...
73
1
def UpperCAmelCase ( lowercase , lowercase ): """simple docstring""" __lowercase = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def UpperCAmelCase ( lowercase , lowercase , ...
210
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __a : str = logging.get_logger(__name__) __a : int = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json""", # See all W...
210
1
from heapq import heappop, heappush import numpy as np def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ,) -> tuple[float | int, list[tuple[int, int]]]: snake_case , snake_case : Dict = grid.shape snake_case : List[Any] ...
176
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedK...
176
1
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets __lowerCamelCase : str = datasets.logging.get_logger(__name__) __lowerCamelCase : str = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, a...
18
"""simple docstring""" import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowercase ( A_ )-> List[Any]: '''simple docstring''' monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_w...
40
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, ...
301
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __lt__( self : Dict , lowerCAmelCase_ :...
301
1
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: lowerCamelCase_ = None try: import msvcrt except ImportError: lowerCamelCase_ = None try: import fcntl except ImportError: lowerCamel...
79
lowerCAmelCase : str = '0.21.0' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches...
253
0
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, ) _A = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHI...
137
from collections import defaultdict class lowerCamelCase : def __init__(self : Tuple , _A : Optional[int] , _A : List[str] ) -> Union[str, Any]: snake_case = total # total no of tasks (N) # DP table will have a...
137
1
"""simple docstring""" import unittest from typing import Dict, List, Optional, Union 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 ImageProcessingSavingTe...
57
"""simple docstring""" def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = 1 while len(_UpperCamelCase ) < 1e6: constant.append(str(_UpperCamelCase ) ) i += 1 __lowerCAmelCase = "".join(_UpperCamelCase...
57
1
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowercase : str = logging.get_logger(__name__) lowercase : Any = { "google/umt5-small": "https://huggingf...
361
'''simple docstring''' # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .util...
160
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer lowercase__ = lo...
96
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''google/bit-50''': ...
141
0
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_ver...
113
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""", ...
113
1
"""simple docstring""" import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, )...
179
"""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...
179
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase ...
5
'''simple docstring''' import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoi...
5
1
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __snake_case ={"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]} try: if not ...
4
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward fro...
325
0
class A : def __init__(self : Optional[Any] ) -> int: """simple docstring""" UpperCAmelCase__ = {} def lowercase_ (self : Optional[Any] ) -> List[Any]: """simple docstring""" print(self.ve...
371
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_...
143
0
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExt...
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] ...
73
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCamelCase_ = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try...
303
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase_ = { 'configuration_mctct': ['MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MCTCTConfig'], 'feature_extraction_mctct': ['MCTCTFeatureExtractor'], ...
303
1
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension...
176
import os from math import logaa def _lowercase ( UpperCamelCase_ = "base_exp.txt" ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(UpperCamelCase_ )...
176
1
"""simple docstring""" from __future__ import annotations from typing import Any def _snake_case ( UpperCamelCase : list[Any] ): create_state_space_tree(lowercase__ , [] , 0 ) def _snake_case ( UpperCamelCase : list[Any] , UpperCamelCase :...
356
"""simple docstring""" def _snake_case ( UpperCamelCase : int , UpperCamelCase : int ): return number | (1 << position) def _snake_case ( UpperCamelCase : int , UpperCamelCase : int ): return number & ~(1 << position) def _snake_case ...
76
0
"""simple docstring""" import random def lowercase (_lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = [], [], [] for element in data: if element < pivot: less.append(_lowerCAmelCase ) ...
301
"""simple docstring""" from math import isqrt, loga def lowercase (_lowerCAmelCase ): __lowerCAmelCase = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , _lowerCAmelCase , ...
301
1
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : list ): def merge(_SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list ) -> list: def _merge(): while left and right: yield (left if ...
352
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __UpperCamelCase ( lowerCAme...
294
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = abs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 0 while n > 0: res += n % 10 n //= 10 return res def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = abs(_UpperCAmelCase) ...
137
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_...
137
1
def A ( _UpperCAmelCase : Union[str, Any] ) -> Any: '''simple docstring''' _UpperCAmelCase = [0] * len(_UpperCAmelCase ) _UpperCAmelCase = [] _UpperCAmelCase = [] _UpperCAmelCase = 0 for values in graph.values(): for i ...
290
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @requ...
290
1
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> int: """simple docstring""" A__ = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): A__ = n - k # Calculate C(n,k) for i in rang...
14
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): ...
160
0
"""simple docstring""" def __UpperCAmelCase ( snake_case_ : Any , snake_case_ : Tuple ) -> Optional[Any]: """simple docstring""" _lowerCAmelCase = [0 for i in range(r + 1 )] # nc0 = 1 _lowerCAmelCase = 1 for i in range(1...
359
"""simple docstring""" import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_ava...
317
0
"""simple docstring""" 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, DDIMScheduler, EulerAncestralDiscreteScheduler, ...
113
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import...
113
1
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCamelCase_ : '''simple docstring''' def __init__( self : Any , UpperCAmelCase__ : Collection[float] | None = None) ->None: ...
231
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: """simple docstring""" return " ".join( ''''''.join(word[::-1] ) if len(lowercase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reve...
231
1
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__ = '''▁''' UpperCAmelCase__...
5
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transfor...
5
1
from maths.prime_check import is_prime def __lowercase ( _UpperCamelCase ) ->int: """simple docstring""" if not isinstance(_UpperCamelCase, _UpperCamelCase ): lowercase : List[str] = f"""Input value of [number={numb...
368
# Algorithm for the pigeonhole sorting def __lowercase ( _UpperCamelCase ) ->List[Any]: """simple docstring""" lowercase : List[Any] = min(_UpperCamelCase ) # min() finds the minimum value lowercase : Union[str, Any] = max(_...
173
0
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _snake_case ( lowerCAmelCas...
18
import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename lowerCAmelCase__ : Union[str, Any] = '''http://www.m...
143
0
"""simple docstring""" import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py __A = '''src/transformers''' __A = '''docs/source/e...
64
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A = logging.get_logger(__name__) __A = { '''ut/deta''': '''https://huggingface.co/ut/deta/resolve/main/config.json''', } class _snake_case ...
64
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 convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI...
303
from heapq import heappop, heappush import numpy as np def a__ ( snake_case , snake_case , snake_case , snake_case , ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = grid.shape __SCREAMING_SNAKE_CASE : Tuple = ...
303
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, ) lowercase : int = {"""configuration_opt""": ["""OPT_PRETRAINE...
359
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine impor...
225
0
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...
26
a_ = 8.314_4598 def lowerCamelCase__ ( _a , _a): if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_ma...
76
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils....
367
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 _snake_case = logging.get_logger(__name...
342
0
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dum...
121
"""simple docstring""" 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 ...
293
0
def A__ ( __lowerCamelCase = 4_00_00_00 ): SCREAMING_SNAKE_CASE_ = [0, 1] SCREAMING_SNAKE_CASE_ = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 SCREAMING_SNAKE_CASE_ = 0 for j in range(len(__lowerCamelC...
351
__UpperCAmelCase = "\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" __UpperCAmelCase = [{"type": "code", "content": INSTALL_CONTENT}] __UpperCAmelCase = { ...
257
0
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path lowercase__ = 'src/transformers' # Matches is_xxx_available() lowercase__ = re.compile(r'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} lowercase__ =...
290
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule lowercase__ = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys lowercase__ = _LazyModule...
290
1
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( """split_dict""" , [ SplitDict(), SplitDict({"""train""": SplitInfo(name="""train""" , num_bytes=1_337 , num_examples=42 , dataset_name="""...
366
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json', # See all BioGPT models at http...
232
0
from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_m...
143
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(se...
349
0
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _A = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ '''text-classification'...
350
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device _A = False class A ( unittest.TestCase ): pass @nightly @requ...
167
0
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split _A = datasets.load_iris() _A = np.array(data["data"]) _A = np.array(data["target"]) _A = data["target_names"] _A, _A, _A, _A = train_test...
231
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class _lowerCAmelCase ( pl.LightningModule ): def __init__( self , _UpperCamelCase ) -> List[str]: super().__i...
231
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', ...
253
"""simple docstring""" from math import factorial lowerCamelCase_ = {str(d): factorial(d) for d in range(10)} def snake_case ( A__ ): return sum(DIGIT_FACTORIAL[d] for d in str(A__ ) ) def snake_case ( ): UpperCAmelCase_ : int = 7 * fac...
253
1