code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from ....configuration_utils import PretrainedConfig from ....utils import logging __a = logging.get_logger(__name__) __a = { 'Visual-Attention-Network/van-base': ( 'https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json' ), } class lowercase__( ...
30
import argparse from collections import defaultdict import yaml __a = 'docs/source/en/_toctree.yml' def a ( snake_case__: Dict ): '''simple docstring''' lowercase_ = defaultdict(snake_case__ ) for doc in model_doc: counts[doc["...
30
1
import mpmath # for roots of unity import numpy as np class a__ : def __init__( self , A=None , A=None ) -> Any: '''simple docstring''' a = list(poly_a or [0] )[:] a = list(poly_b or [0] )[:] # Remove leading zero ...
360
import math import unittest def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> bool: assert isinstance(__UpperCamelCase , __UpperCamelCase) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return ...
180
0
"""simple docstring""" import math def lowercase ( a__ : int , a__ : Union[str, Any] ) -> Any: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(a__ ) else: if x == 0: # 0 raised to any num...
256
"""simple docstring""" import logging from transformers import PretrainedConfig UpperCAmelCase = logging.getLogger(__name__) UpperCAmelCase = { """bertabs-finetuned-cnndm""": """https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json""", ...
256
1
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Union[str, Any] , ...
362
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_prope...
204
0
"""simple docstring""" import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCa...
105
"""simple docstring""" import heapq as hq import math from collections.abc import Iterator class __UpperCamelCase : def __init__( self , lowerCAmelCase__ ) -> Optional[int]: a : List[str] = str(id_ ) a : Opti...
105
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''', ...
367
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str | Literal[False]: A: List[str] = list(__lowercase ) A: ...
334
0
'''simple docstring''' def UpperCamelCase ( _lowerCamelCase : list ): A__ = False while is_sorted is False: # Until all the indices are traversed keep looping A__ = True for i in range(0 , len(_lowerCamelCase ) - 1 , 2 ...
237
'''simple docstring''' import warnings warnings.warn( "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: " "`from accelerate import find_executable_batch_size` to avoid this warning.", FutureWarning, )
237
1
def A ( lowercase = 1_000_000 ) -> int: '''simple docstring''' UpperCamelCase = limit + 1 UpperCamelCase = [0] * limit for first_term in range(1 , lowercase ): for n in range(lowercase , lowercase , lowercase ): UpperCamelCase = first_ter...
352
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_comm...
110
0
import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArgument...
36
'''simple docstring''' import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_co...
70
0
"""simple docstring""" def lowerCamelCase (a_ :float , a_ :float , a_ :int) -> float: if principal <= 0: raise Exception('''Principal borrowed must be > 0''') if rate_per_annum < 0: raise Exception('''Rate of interest must be >= 0''') if y...
172
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = '''\ @misc{chen2021evaluating, title={Evalu...
172
1
'''simple docstring''' from collections.abc import Sequence def lowerCAmelCase (__A , __A = False): """simple docstring""" if not arr: return 0 _a = 0 if allow_empty_subarrays else float('''-inf''') _a = 0.0 for num in arr: _a = max(0 ...
211
'''simple docstring''' import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokeni...
211
1
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline ...
340
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase : List[str] = logging.get_logger(__name__) _lowerCA...
340
1
import math import tensorflow as tf from packaging import version def _a ( a :Any ) -> Union[str, Any]: a = tf.convert_to_tensor(a ) a = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def _a ( a :Unio...
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_d...
0
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase :Tuple = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBl...
68
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase :int = logging.get_logger(__name__) _lowerCAmelCase :Union[str, Any] = { 'xlm-mlm-...
68
1
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging _UpperCAmelCase : Dict = logging.get_logger(__name__) class lowerCAmelCase : UpperCAmelCase__ = None @experimental def SCREAMING_SNAKE_...
50
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_...
180
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from ...
236
'''simple docstring''' from datetime import datetime import requests def A__ ( UpperCAmelCase_ ): _UpperCamelCase : List[Any] = 'https://downloadgram.net/wp-json/wppress/video-downloader/video?url=' _UpperCamelCase : Optional[int] = requests.get(base_url + ur...
236
1
'''simple docstring''' class SCREAMING_SNAKE_CASE : def __init__( self , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): '''simple docstring''' __A : Tuple = data __A : List[Any] ...
190
def _SCREAMING_SNAKE_CASE ( lowercase : int = 10_00 ): '''simple docstring''' lowerCamelCase_ = 2**power lowerCamelCase_ = 0 while n: lowerCamelCase_ , lowerCamelCase_ = r + n % 10, n // 10 return ...
204
0
from __future__ import annotations def a__ ( A__, A__ ): if len(A__ ) == 0: return False SCREAMING_SNAKE_CASE_ : int = len(A__ ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary...
162
import math import unittest def a__ ( A__ ): assert isinstance(A__, A__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3...
162
1
"""simple docstring""" def _snake_case ( UpperCAmelCase_ : float ): if edge <= 0 or not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise ValueError("""Length must be a positive.""" ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) ...
335
"""simple docstring""" import math def _snake_case ( UpperCAmelCase_ : float , UpperCAmelCase_ : float ): if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of ini...
335
1
def lowerCAmelCase_ ( _lowercase : int = 1000) -> int: """simple docstring""" return sum(e for e in range(3 , _lowercase) if e % 3 == 0 or e % 5 == 0) if __name__ == "__main__": print(f'{solution() = }')
266
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : str =logging.getLogger(__name__) @dataclass class snake_case__ (A__ ): ...
266
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _...
90
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @...
110
0
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers c...
121
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function lowerCAmelCase__ = 1.054571817e-34 # unit of ℏ : J * s lowerCAmelCase__ = 3e8 # unit of c : m * s^-1 def __lowerCamelCase ( lowerCamelCa...
121
1
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def __UpperCAmelCase ( UpperCAmelCase_ ...
172
"""simple docstring""" import os import pytest from attr import dataclass _a : Optional[int]= "us-east-1" # defaults region @dataclass class UpperCamelCase : UpperCAmelCase : str UpperCAmelCase : Any = """arn:aws:iam::558105141721:role/sagemaker_exe...
172
1
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": UpperCamelCase = """%20""".join(argv[1:]) if len(argv) > 1 else quote(str(input("""Search: """))) print...
65
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ): if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif electr...
65
1
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate...
340
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/en/tasks''' def ...
340
1
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Versi...
219
'''simple docstring''' from __future__ import annotations import math def a ( __a ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives,...
219
1
import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging lo...
68
from collections import deque from math import floor from random import random from time import time class a__ : """simple docstring""" def __init__( self ) -> Dict: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase ,...
68
1
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): a_ = { "linear": PIL.Image.Resampling.BILINEAR, "bilinear": PIL.Image.Resam...
357
'''simple docstring''' 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.ut...
222
0
"""simple docstring""" import json import sys def _SCREAMING_SNAKE_CASE ( __snake_case : List[str] , __snake_case : Optional[Any] ): '''simple docstring''' with open(_a , encoding='utf-8' ) as f: lowercase = json.load(_a ) lowercase ...
220
"""simple docstring""" from functools import lru_cache @lru_cache def __lowercase ( _a ): if num < 0: raise ValueError('''Number should not be negative.''' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest...
264
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : Optional[int] = { """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.js...
352
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : Tuple = logging.get_logger(__name__) class A__ ( __snake_case ): _UpperCAmelCase :List[Any] = 'timm_backbone' def __init__( self , A_=None , ...
140
0
'''simple docstring''' from collections import namedtuple import requests from lxml import html # type: ignore __lowerCamelCase = namedtuple('''covid_data''', '''cases deaths recovered''') def UpperCAmelCase__ ( UpperCAmelCase__ = "https://www.worldometers.info/coronavirus/" ) -> covid...
162
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self , UpperCamelCase__=None ) -> Any: '''simple docstring''' A_ = data A_ = None def __repr__( self ) -> List[str]:...
162
1
UpperCAmelCase_ : int = 8.31_4462 # Unit - J mol-1 K-1 def UpperCamelCase ( _A : float , _A : float , _A : float )-> float: """simple docstring""" if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Inval...
366
def UpperCamelCase ( _A : str )-> str: """simple docstring""" A__ = "" 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 UpperCamelCase ( _A...
198
0
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union lowercase_ = re.compile(R'^(?P<major>\d+)' R'\.(?P<minor>\d+)' R'\.(?P<patch>\d+)$') @total_ordering @dataclass class ...
266
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("...
266
1
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput ...
6
'''simple docstring''' from argparse import ArgumentParser from . import BaseTransformersCLICommand def a_ ( __snake_case : Tuple ) -> str: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force ,...
6
1
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex UpperCAmelCase__ : Dict = logging.getLogger(__name__) class UpperCAmelCase : '''simple docstring''' def __init...
121
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 lowerCamelCase__ ( a ) ->...
121
1
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCamelCase_ (a__ , unittest.TestCase ): __magic_name__ = PhobertTokenizer __mag...
369
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..ut...
253
0
def lowerCAmelCase_ ( __A, __A, __A, __A ) -> List[Any]: '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: UpperCAmelCase__ = mf_knapsack(i - 1, __A, __A, __A ...
65
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = [ "encoder.version", "dec...
65
1
from math import pi, sqrt def __snake_case ( _lowerCAmelCase : float ) -> float: if num <= 0: raise ValueError("math domain error" ) if num > 171.5: raise OverflowError("math range error" ) elif num - int(_lowerCAmelCase ) not in (0, 0.5): raise NotImplementedError("num ...
368
import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configura...
70
0
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='''%(message)s''') def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : np.ndarray ) -> np.ndarray: """simple docstring""" return ...
219
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_...
219
1
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 SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger...
360
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Any = TypeVar("KEY") SCREAMING_SNAKE_CASE__ : Dict = TypeVar("VAL") @dataclass(frozen=__lowercase , slots=__lowercase )...
339
0
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, requi...
271
'''simple docstring''' class UpperCAmelCase__ : """simple docstring""" def __init__( self : Dict ): '''simple docstring''' _a : Dict = {} def __lowercase ( self : Union[str, Any] ): '''simple docstring''' print(self.vert...
271
1
'''simple docstring''' def __A ( lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : Any = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): _UpperCAmelCase : Any = n - k # Calculate C(n,k) for i in range(lowerCAmelCase_ ): ...
170
'''simple docstring''' import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_...
170
1
# 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...
140
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils imp...
140
1
import flax.linen as nn import jax import jax.numpy as jnp class _A ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def A__ ( self ): """simple docstring""" ...
371
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): fr...
32
0
"""simple docstring""" from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE_ : """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 0): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_C...
100
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoMode...
198
0
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import C...
370
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetC...
171
0
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 __lowerCAmelCase ( a...
6
def __lowerCAmelCase ( a__ , a__ , a__ ) -> list: __a = len(a__ ) __a = [[0] * n for i in range(a__ )] for i in range(a__ ): __a = y_points[i] for i in range(2 , a__ ): for j in range(a__ , a__ ): ...
6
1
import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class _lowerCAmelCase ( _UpperCAmelCase )...
352
import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowerCAmelCase_ = logging.get_logger(__name__) class _lowerCAmelCase ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , ...
260
0
from collections import deque from math import floor from random import random from time import time class lowerCamelCase : '''simple docstring''' def __init__( self ) -> Optional[int]: UpperCAmelCase_ : Dict = {} ...
29
import argparse from collections import defaultdict import yaml lowerCAmelCase : Dict = 'docs/source/en/_toctree.yml' def A_ ( a ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = defaultdict(a ) for doc in model_doc: ...
253
0
from __future__ import annotations from fractions import Fraction def UpperCamelCase__( UpperCamelCase__ : int , UpperCamelCase__ : int )->bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def U...
39
# Algorithm for the pigeonhole sorting def UpperCamelCase__( UpperCamelCase__ : int )->str: A__ = min(UpperCamelCase__ ) # min() finds the minimum value A__ = max(UpperCamelCase__ ) # max() finds the maximum value A__ = max_v...
39
1
def __a ( SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' if upper_limit < 0: raise ValueError('''Limit for the Catalan sequence must be ≥ 0''' ) __UpperCAmelCase = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 ...
333
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokeniz...
70
0
"""simple docstring""" import os import pytest from transformers.dynamic_module_utils import get_imports _a : List[Any]= "\nimport os\n" _a : List[str]= "\ndef foo():\n import os\n return False\n" _a : Dict= "\ndef foo():\n def bar():\n if Tr...
95
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def __UpperCAmelCase ( UpperCAmelCase_ : int ) -> str: '''simple docstring''' if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise TypeError('Un...
95
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : List[str] = {"configuration_encoder_decoder": ["EncoderDecoderConf...
136
"""simple docstring""" def A ( snake_case :int ) -> int: __UpperCamelCase = [1] __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 0, 0, 0 __UpperCamelCase = ugly_nums[ia] * 2 __UpperCamelCase = ugly_nums[ia] * 3 __UpperCamelCase ...
316
0
from __future__ import annotations from typing import Any def __lowerCamelCase ( UpperCAmelCase_ : list[Any] ): """simple docstring""" create_state_space_tree(UpperCAmelCase_ , [] , 0 ) def __lowerCamelCase ( UpperCAmelCase_ : list[Any] , Upp...
281
from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...tes...
281
1
import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStru...
170
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"} class snake_case__ (A__ ): ...
170
1
SCREAMING_SNAKE_CASE_:List[str] = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100_000)] def __UpperCamelCase ( _lowerCAmelCase ) -> int: """simple docstring""" A : Optional[int] = 0 while number: # Increased Speed Slightly by check...
115
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE_:int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_:Any = { """roberta-base""": """https...
115
1
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self , __lowercase , __lowercase) -> Optional[int]: __UpperCamelCase :Any = params _...
43
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_...
32
0
import argparse import os import re import packaging.version __UpperCAmelCase = '''examples/''' __UpperCAmelCase = { '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([...
103
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from .....
103
1
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #...
61
"""simple docstring""" import os from datetime import datetime as dt from github import Github _A = [ """good first issue""", """feature request""", """wip""", ] def a__ ( ) -> str: UpperCAmelCase__ : Union[str, Any] = Github(os.environ["""GITHUB_TOKEN"""] ...
171
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenizat...
370
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tenso...
324
0
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 lowerCAmelCase__ ( a): '''simple docstring''...
11
"""simple docstring""" import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging __A : Union[str, Any] = "\\n\n" __A : Any = "\nPerplexity...
260
0
def lowerCamelCase__ ( a__ : Optional[int] , a__ : Any ) -> Optional[Any]: UpperCamelCase_ = 0 UpperCamelCase_ = len(a__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_co...
261
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def lowerCamelCase__ ( a__ : Dataset , a__ : Dict[str, str] ) -> int: UpperCamelCase_ ...
261
1
from __future__ import annotations from typing import Any def __A ( __lowerCAmelCase )-> int: """simple docstring""" if not postfix_notation: return 0 _UpperCAmelCase = {'+', '-', '*', '/'} _UpperCAmelCase = []...
39
from __future__ import annotations import collections import pprint from pathlib import Path def __A ( __lowerCAmelCase )-> str: """simple docstring""" return "".join(sorted(__lowerCAmelCase ) ) def __A ( __lowerCAmelCase )-> list[str]: ...
39
1
"""simple docstring""" import random from .binary_exp_mod import bin_exp_mod def lowerCAmelCase__ ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[int]=1_0_0_0 ) -> Any: """simple docstring""" if n < 2: return False ...
149
"""simple docstring""" from __future__ import annotations from typing import Any class lowerCAmelCase_ ( lowerCAmelCase ): """simple docstring""" pass class lowerCAmelCase_ : """simple docstring""" def __init__( self , lowerCA...
149
1
from __future__ import annotations from random import choice def _A ( SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return choice(SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CA...
95
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...
95
1
"""simple docstring""" from dataclasses import dataclass, field from typing import Optional @dataclass class _lowercase : lowercase_ = field( default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be trained.'} ) lowercase_ = field( ...
205
"""simple docstring""" def UpperCAmelCase ( ): '''simple docstring''' return 1 def UpperCAmelCase ( a_ ): '''simple docstring''' return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def UpperCAmelCase ( a_ ): '''simple docstring''' ...
205
1
from bisect import bisect from itertools import accumulate def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' snake_case_ = sorted(zip(UpperCamelCase__ , UpperCame...
285
import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simp...
285
1
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable UpperCamelCase = {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]} try: ...
65
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, t...
65
1
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics...
115
"""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...
115
1
'''simple docstring''' 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, requ...
219
'''simple docstring''' import argparse from collections import defaultdict import yaml __snake_case = '''docs/source/en/_toctree.yml''' def a ( __a ) -> int: '''simple docstring''' UpperCamelCase__ :int = defaultdict(__a ) Upper...
219
1
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 A__ : int = logging.get_logger(__name__) A__ : List[Any] = ...
103
import string def UpperCamelCase( __UpperCamelCase : str ): for key in range(len(string.ascii_uppercase ) ): lowerCAmelCase_ : List[Any] = '''''' for symbol in message: if symbol in string.ascii_uppercase: lowerCAmelCase_ : Optional[int] = string.asci...
103
1
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): i...
367
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() ...
205
0
'''simple docstring''' import math def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> float: if ( not isinstance(__A , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('power_factor must be a valid float value between -1 and 1.' ) return appar...
42
'''simple docstring''' import os import numpy import onnx def a__ ( lowercase : List[str], lowercase : str ) -> List[Any]: """simple docstring""" _UpperCamelCase = a.name _UpperCamelCase = b.name _UpperCamelCase ...
324
0
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE ( lowercase__ ): """simple docstring""...
358
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_b...
139
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__:List[Any] = {"""configuration_fnet""": ["""FNET_PRETRAINED...
261
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data im...
261
1
import numpy as np def __lowerCamelCase ( __magic_name__ : np.ndarray , __magic_name__ : np.ndarray , __magic_name__ : float = 1e-12 , __magic_name__ : int = 100 , ): assert np.shape(__magic_name__ )[0] == np.shape(__magic_name__ )[1] # Ensure pr...
360
def __lowerCamelCase ( __magic_name__ : int ): if not isinstance(__magic_name__ , __magic_name__ ): a__: List[str] =F"Input value of [number={number}] must be an integer" raise TypeError(__magic_name__ ) if number < 1: a__: ...
42
0
from torch import nn def lowerCAmelCase_ ( A_): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F"Unsupported activation funct...
149
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_ ,A_): UpperCamelCase__: List[str] = cva.getAffineTransform(A_ ,A_) return cva.warpAffine(A_ ,A_ ,(rows, cols)) if...
149
1
import os import sys import unittest __magic_name__ = 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, ...
359
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = {} try: if not is_sentencepiece_available(): raise Optio...
152
0
def a ( A__ : Optional[int]=28123 ) -> Any: """simple docstring""" _lowercase =[1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i +...
205
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_ = { 'configuration_pix2struct': [ 'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Pix2StructConfig', 'Pix2StructTextCon...
205
1
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = (IPNDMScheduler,) snake_case__ : str = (('''num_in...
120
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 UpperCAmelCase_ : str = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classifi...
120
1
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tenso...
65
from __future__ import annotations from collections import deque class A : def __init__(self : Dict , __UpperCAmelCase : list[str] ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = [] self.adlist.a...
65
1
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_...
359
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase__ : List[Any] =logging.get_logger(__name__) lowerCAmelCase__ : Tuple ={ 'micros...
162
0
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfil...
90
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 : int = '''▁''' lowerCamelCase : Optional[int] = ...
233
0
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class _lowerCAmelCase ( snake_case_ ): __UpperCAmelCase : Dict = '''Speech2TextFeatureExtractor''' __UpperCAmelCase : Optional[Any] = '''Speech2Te...
369
"""simple docstring""" import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _lowerCAmelCase ( unit...
112
0
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testi...
79
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import...
205
0
from __future__ import annotations def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> list[list[int]]: lowerCAmelCase__ : list[list[int]] = [] create_all_state(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , [] , SCREA...
307
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 lowerCAmelCase__ ...
307
1
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...
5
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def A_ ( snake_case ): SCREAMING_SNAKE_CASE:int = test_file.spli...
139
0
_SCREAMING_SNAKE_CASE = """ # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git """ _SCREAMING_SNAKE_CASE = [{"""type""": """code""", """content""": INSTALL_CONTENT}] _S...
356
def SCREAMING_SNAKE_CASE__ ( __a , __a = False ): if not isinstance(__a , __a ): snake_case_ : str = f"""Expected string as input, found {type(__a )}""" raise ValueError(__a ) if not isinstance(__a , __a ): snake_case_ : int = f...
88
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/LICENS...
54
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transfor...
42
0
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_ = """▁""" UpperCAmelCase_ = {"""vocab_file""": """spiece.model"""}...
295
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class UpperCamelCase_ ( enum.Enum ): ...
295
1
"""simple docstring""" import unittest import numpy as np def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = None, ): UpperCAmelCase_ : Any = np.shape(UpperCamelCase__ ) UpperCAmelCase_ : Dict = np.shape(UpperCamelCase__ ...
61
'''simple docstring''' from __future__ import annotations def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' if not nums: return 0 SCREAMING_SNAKE_CASE__ : Dict =nums[0] SCREAMING_SNAKE_CAS...
152
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_clipseg""": [ """CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPSegConfig""", """CLIPSegTextConfig""", """CLI...
319
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger snake_case = get_logger(__name__) snake_case = r""" Args: input_ids (`jnp.ndarray` of shape `(batch_size, sequence_le...
319
1
'''simple docstring''' def UpperCamelCase_ ( A__ : Tuple , A__ : Union[str, Any] ): '''simple docstring''' lowerCAmelCase_ : Any = """""" for i in table: res += inp[i - 1] return res def UpperCamelCase_ ( ...
120
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __snake_ca...
120
1
from math import factorial def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 20 ): __UpperCamelCase =2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... __UpperCamelCase =n // 2 return int(factorial(SCREAMING_SNAKE...
117
from ....utils import logging _A = logging.get_logger(__name__) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_=None , A_=2048 ) -> Any: __UpperCamelCase =config.__dict__ __UpperCamelCase ...
117
1
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": _UpperCAmelCase : str = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, ...
50
'''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 __lowerCamelCase = '''src/transformers''' __lowe...
162
0
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-g...
328
import re from filelock import FileLock try: import nltk _UpperCAmelCase = True except (ImportError, ModuleNotFoundError): _UpperCAmelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCAmelCase_ ( U...
328
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" A__ = 0 A__ = len(_lowerCamelCase ) - 1 while i < j: ...
221
'''simple docstring''' def lowerCAmelCase_ ( _lowerCamelCase: float , _lowerCamelCase: list[float] ): if discount_rate < 0: raise ValueError("""Discount rate cannot be negative""" ) if not cash_flows: raise ValueError("""Cash flows list cannot be empty""" ) __SCREA...
112
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_config...
65
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import ...
65
1
import numpy as np from PIL import Image def a_ ( _A , _A , _A ) -> np.ndarray: """simple docstring""" snake_case__ = np.array(_A ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a squar...
307
def a_ ( _A = 1000 ) -> int: """simple docstring""" return sum(e for e in range(3 , _A ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f'''{solution() = }''')
307
1
"""simple docstring""" import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def SCREAMING_S...
352
from math import pi def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> float: """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
62
0