code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
166
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig A__ = logging.get_logger(__name__) A__ = { """Intel/dpt-large""": """https://huggingface.co/Intel/dpt-large/resolve/main/config.json""", # See all DPT models at h...
166
1
from math import sqrt def lowerCamelCase__ ( lowercase = 1000000 ): """simple docstring""" SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : int while num_cuboids <= limit: max_cuboid_size += ...
714
import warnings 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 snake_case = logging.get_logger(__name__) snake_case = { """nvidia/...
488
0
'''simple docstring''' A_ = "\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" A_ = [{"type": "code", "content": INSTALL_CONTENT}] A_ = ...
143
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: fr...
143
1
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_att...
246
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def lowerCAmelCase( __lowerCamelCase ): # A local function to see if a dot lands in the circle. def is_in_circle(__lowerCamelCase , __lowerCamelCase ) -> bool: ...
246
1
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memor...
472
'''simple docstring''' import argparse import copy def _A ( UpperCAmelCase ): '''simple docstring''' A__ = {} with open(UpperCAmelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: A__ = ...
531
0
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_jso...
586
from __future__ import annotations import unittest from transformers import RoFormerConfig, 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...
586
1
"""simple docstring""" import numpy as np import qiskit def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__ = 8, SCREAMING_SNAKE_CASE__ = None ) -> str: a_ : Any = np.random.default_rng(seed=SCREAMING_SNAKE_CASE__ ) # Roughly 25% of the qubits will contribute to the key. ...
237
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class snake_case_ ( a_ ): __lowerCA...
237
1
'''simple docstring''' import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value...
398
'''simple docstring''' def UpperCamelCase_ ( A__ : int ): '''simple docstring''' if not isinstance(A__ , A__ ) or number < 0: raise ValueError("""Input must be a non-negative integer""" ) lowerCAmelCase_ : List[str] = ...
398
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { 'huggingface/informer-tourism-monthly': ( 'https://huggingface.co/huggingface/informer-tourism-monthly...
464
'''simple docstring''' from typing import Any class A : def __init__( self , lowerCamelCase__ ) -> Dict: '''simple docstring''' lowercase__ = data lowercase__ = None def __repr__( self ) -> ...
325
0
"""simple docstring""" import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_...
706
"""simple docstring""" def snake_case__ ( _SCREAMING_SNAKE_CASE ) ->Tuple: # noqa: E741 UpperCAmelCase__ = len(_SCREAMING_SNAKE_CASE ) UpperCAmelCase__ = 0 UpperCAmelCase__ = [0] * n UpperCAmelCase__ = [False] * n UpperCAmelCase__ = [False] * n ...
422
0
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if num <= 0: raise ValueError("Input must be a positive integer" ) _UpperCAmelCase = [True] * (num + 1) _UpperCAmelCase = 2 while p * p <= num: if primes[p]: for i in range(p * p , nu...
657
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = { "en": "Machine learning is grea...
657
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _A = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ...
718
import argparse import json import subprocess def __SCREAMING_SNAKE_CASE ( UpperCamelCase : List[str] , UpperCamelCase : Tuple ) -> Dict: """simple docstring""" a_ = [] a_ = ( F"""curl -H \"Accept: application/vnd.github+json\" -H \"Authorization: Bearer {toke...
403
0
from __future__ import annotations import math def __UpperCAmelCase ( __A ) -> list[int]: '''simple docstring''' if num <= 0: UpperCAmelCase__ = F"""{num}: Invalid input, please enter a positive integer.""" r...
475
import math import unittest def __UpperCAmelCase ( __A ) -> bool: '''simple docstring''' assert isinstance(__A , __A ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: ...
475
1
def lowercase ( SCREAMING_SNAKE_CASE__ : int = 1_000 ) -> int: _snake_case : List[Any] = 2**power _snake_case : Optional[Any] = 0 while n: _snake_case : Optional[int] = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(in...
708
from __future__ import annotations import unittest from transformers import 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_mask from ...
198
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def snake_case_ (UpperCamelCase : Callable[[int | float], int | float] , UpperCamelCase : int | float , UpperCamelCase : int | float , UpperCamelCase : int = 1...
22
'''simple docstring''' def lowerCamelCase_ ( A_ = 60_08_51_47_51_43 ): try: __lowerCamelCase = int(A_ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or...
316
0
"""simple docstring""" import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from tra...
42
"""simple docstring""" import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identifie...
42
1
import inspect import os import re from transformers.configuration_utils import PretrainedConfig 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_config_docstrings.py __A : List[...
343
from typing import Dict, Optional import numpy as np import datasets __A : Any = ''' IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentati...
343
1
'''simple docstring''' from __future__ import annotations UpperCamelCase__ : Optional[Any] = list[list[int]] # assigning initial values to the grid UpperCamelCase__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], ...
178
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def lowerCAmelCase_ ( _l...
178
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : int | float | str ) -> tuple[int, int]: try: _lowercase = float(SCREAMING_SNAKE_CASE_ ) except ValueError: raise ValueError("""Please enter a valid number""" ) _lowercase = ...
287
from __future__ import annotations def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more ...
287
1
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __a : Dict = logging.get_logger(__name__) __a : Any = {""...
559
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 .tokenizati...
559
1
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter a_ :Optional[int] = True except ImportEr...
478
import requests SCREAMING_SNAKE_CASE = "" # <-- Put your OpenWeatherMap appid here! SCREAMING_SNAKE_CASE = "https://api.openweathermap.org/data/2.5/" def snake_case__ ( __SCREAMING_SNAKE_CASE = "Chicago" , __SCREAMING_SNAKE_CASE = APPID ) -> dict: return requests.get(UR...
579
0
from decimal import Decimal, getcontext from math import ceil, factorial def a__ ( snake_case ) -> List[Any]: """simple docstring""" if not isinstance(snake_case , snake_case ): raise TypeError('''Undefined for non-integers''' ) elif precision < 1: rais...
712
from math import pi, sqrt def a__ ( snake_case ): """simple docstring""" if num <= 0: raise ValueError('''math domain error''' ) if num > 171.5: raise OverflowError('''math range error''' ) elif num - int(snake_case ) not in (0, 0.5): raise NotImplemen...
131
0
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCamelCase : Optional[int] = False class A__ ...
405
from maths.prime_check import is_prime def _SCREAMING_SNAKE_CASE ( lowercase : int ): '''simple docstring''' if not isinstance(lowercase , lowercase ): lowerCamelCase_ = f"""Input value of [number={number}] must be an integer""" ...
70
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class _a ( metaclass=SCREAMING_SNAKE_CASE ): '''simple docstring''' A : Optional[Any] = ['''speech'''] def __init__( self, *A, ...
708
'''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 ...onnx...
508
0
'''simple docstring''' class a_ : def __init__( self ): _lowerCAmelCase : Optional[int] = 0 _lowerCAmelCase : Any = 0 _lowerCAmelCase : List[Any] = {} def __UpperCamelCase ( self , snake_case_ ): ...
384
'''simple docstring''' UpperCamelCase_ = 8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def _UpperCAmelCase ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ) -> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError(""...
384
1
"""simple docstring""" 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"""...
36
"""simple docstring""" import string def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] ="""""" for i in sequence: SCREAMING_SNAKE_CASE_: List[Any] =ord(lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) ...
36
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/config.js...
365
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowercase ( ): __A : List[Any] = ArgumentParser( description=( 'PyTorch TPU distributed tra...
365
1
"""simple docstring""" 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 is ...
702
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() exc...
217
0
"""simple docstring""" import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils impor...
218
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def lowercase__(A ) ->list[list[float]]: """simple docstring""" lowercase__ : str= Decimal # Check if the prov...
218
1
import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTes...
705
def A ( UpperCAmelCase ): if n == 1 or not isinstance(UpperCAmelCase , UpperCAmelCase ): return 0 elif n == 2: return 1 else: _snake_case : List[Any] = [0, 1] for i in range(2 , n + 1 ): ...
278
0
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def __UpperCAmelCase ( ) -> None: """simple docstring""" print('''Making key files...''' ) make_key_files('''r...
14
def lowercase( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: '''simple docstring''' _enforce_args(UpperCamelCase_ , UpperCamelCase_ ) if n == 0: return 0 UpperCamelCase = float("""-inf""" ) for i in range(1 , n + 1 ): UpperCamelCase ...
537
0
from PIL import Image def snake_case__ ( _SCREAMING_SNAKE_CASE ) ->Image: UpperCAmelCase__ = image.size UpperCAmelCase__ = 0 UpperCAmelCase__ = image.load() for i in range(lowercase_ ): for j in range(lowercase_ ): UpperCAmelCase__ = pixels[j, i] ...
720
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_...
422
0
"""simple docstring""" def UpperCAmelCase ( A : Optional[Any] , A : Any ): '''simple docstring''' _UpperCAmelCase = [0 for i in range(r + 1 )] # nc0 = 1 _UpperCAmelCase = 1 for i in range(1 , n + 1 ): # to com...
573
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(): ...
687
0
'''simple docstring''' from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE ( __lowercase): """simple docstring""" lowercase : Union[str, Any] = 'ClapFeatureExtractor' lowercase : List[Any] =...
58
'''simple docstring''' import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from tran...
58
1
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffuser...
24
class UpperCAmelCase_ : """simple docstring""" def __init__( self , _a , _a , _a ) -> List[str]: _a : List[Any] = name _a : List[str] = value _a : List[str...
14
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor Uppe...
312
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin ...
312
1
"""simple docstring""" 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...
650
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_ten...
80
0
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class lowerCAmelCase__ ( __lowerCamelCase ): ""...
73
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAme...
73
1
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask A_: Dict = logging.getLogger(__name__) class _lowercase ( A_ ): """simple docstring""" def __init__( se...
398
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _lowercase = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwiftFormerConfig''', '''SwiftFormerOnnx...
157
0
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .atten...
342
"""simple docstring""" from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import T...
342
1
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE ) class _a ( SCREAMING_SNAKE_CASE ): ...
28
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_...
682
0
'''simple docstring''' import enum import shutil import sys _lowerCAmelCase , _lowerCAmelCase : Tuple = shutil.get_terminal_size() _lowerCAmelCase : List[Any] = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase ( enum.Enum ): _lowerCamelCase :...
646
'''simple docstring''' import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowerCAmelCase : Union[str, Any] = get_tests_dir('fixture...
646
1
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 loggi...
79
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.t...
79
1
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("dataset_size" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("input_in_memory_max_size" , ["default", 0, 100 * 2**20, 900 * 2**20] ) def lowerCamelCase...
488
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils....
488
1
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_util...
551
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), ...
551
1
_UpperCAmelCase = {'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []} _UpperCAmelCase = ['''a''', '''b''', '''c''', '''d''', '''e'''] def UpperCamelCase ( __lowercase : Dict ,__lowercase : Tuple ,__lowercase : Union[str, Any] ...
710
def UpperCamelCase ( __lowercase : str ,__lowercase : int ): '''simple docstring''' A_ : int = word.split() def justify(__lowercase : list ,__lowercase : int ,__lowercase : int ) -> str: A_ : Optional[Any] = max_width - width...
70
0
"""simple docstring""" import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBer...
123
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) lowercase__ : List[Any] = {'''configuration_beit''': ['''BEIT_PRETRAINED_CONFIG_AR...
123
1
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) def a_ (_lowerCAmelCase : int )-> Tup...
164
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCamelCase ( __snake_case ): __lowerCamelCase = ['image_processor', 'tokenizer'] __lowerCamelCase = 'AutoImageProcessor' __lowerCamelCase = 'AutoT...
164
1
'''simple docstring''' from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transform...
261
'''simple docstring''' def _A ( snake_case__ : list[int] , snake_case__ : list[int] ): snake_case__ : Tuple = len(snake_case__ ) print('''The following activities are selected:''' ) # The first activity is always selected snake_case__ : Optional[Any] ...
261
1
def lowerCAmelCase_ ( snake_case_ ): _A : Union[str, Any] = len(snake_case_ ) for _ in range(snake_case_ ): for i in range(_ % 2,arr_size - 1,2 ): if arr[i + 1] < arr[i]: _A : Tuple = arr[i + 1], arr[i] ret...
710
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_be...
54
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) # pylint:...
444
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCAmelCase : int ...
444
1
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def snake_case_ ( lowercase__ : str ): '''simple docstring''' _lowerCAmelCase =analyze_text(snake_case__ ) _lowerCAmelCas...
706
from typing import TYPE_CHECKING from ...utils import _LazyModule __SCREAMING_SNAKE_CASE : Optional[Any] = {'''tokenization_wav2vec2_phoneme''': ['''Wav2Vec2PhonemeCTCTokenizer''']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys ...
149
0
"""simple docstring""" import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from...
434
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : str ={'configuration_mmbt': ['MMBTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() ex...
434
1
def _lowerCamelCase ( snake_case , snake_case ): def get_matched_characters(snake_case , snake_case ) -> str: _lowerCAmelCase = [] _lowerCAmelCase = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumer...
225
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils imp...
225
1
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = [[] for _ in range(SCREAMING_SNAKE_CASE__ )] snake_case_ = key - 1 if key <= 0: raise ValueError('''Height of grid can\'t be 0 or negative''' ) if k...
39
"""simple docstring""" import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import ...
535
0
'''simple docstring''' import gc import threading import time import psutil import torch class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple ): """simple docstring""" __snake_case = psutil.Process() __snake_case =...
680
'''simple docstring''' import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch a : Dict = '''...
680
1
'''simple docstring''' import os import time import numpy as np import onnxruntime as ort lowerCamelCase = """1""" lowerCamelCase = """0""" lowerCamelCase = """1""" lowerCamelCase = ort.SessionOptions() lowerCamelCase = ort.GraphOptimizati...
474
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE_ = { '''configuration_roc_bert''': ['''ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoCBertConfig'''...
373
0
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup...
713
'''simple docstring''' from __future__ import annotations import pandas as pd def __snake_case ( UpperCAmelCase_ : list[int] , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : int ): lowerCamelCase_ = [0] * no_of_processes lowerCamelCase_ = ...
445
0
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _SCREAMING_SNAKE_CA...
107
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) _SCREAMING_SNAKE_CASE =str(bin(_UpperCamel...
405
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {"vocab_file": "sen...
715
# 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 ( low...
594
0
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils impo...
88
'''simple docstring''' from __future__ import annotations from scipy.special import comb # type: ignore class UpperCAmelCase_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : list[tuple[float, float]] ) -> Optional[int]: lowerC...
133
0
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def UpperCAmelCase ( snake_case : int , snake_case : str , snake_case : Union[str, Any] , snake_case : List[Any] ): _lowerCAmelCase:...
439
"""simple docstring""" import baseaa def UpperCAmelCase ( snake_case : str ): return baseaa.aaaencode(string.encode('''utf-8''' ) ) def UpperCAmelCase ( snake_case : bytes ): return baseaa.aaadecode(snake_case ).decode('''utf-8''' ) if __n...
439
1
from __future__ import annotations _snake_case : Union[str, Any] = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class a : """simple docstring""" def __in...
81
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor __UpperCamelCase : Optional[int] = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): def __init__( self :Union[str, Any] ...
468
0
from __future__ import annotations from typing import Generic, TypeVar _SCREAMING_SNAKE_CASE : List[str] = TypeVar('''T''') class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Optional[Any] , __lowerCamelCase : List[Any] ) -> ...
708
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...token...
472
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence,...
26
'''simple docstring''' 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 d...
26
1
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class a__ ( UpperCAmelCase ): """simple docstring""" UpperCAmelCase__ : List[str] ="""Speech2TextFeatureExtractor""" UpperCAmelCas...
446
from __future__ import annotations import numpy as np def __lowercase ( _A ) -> tuple[np.ndarray, np.ndarray]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = np.shape(_A ) if rows != columns: SCREAMING_SNAKE_CASE : int...
446
1
'''simple docstring''' def UpperCAmelCase__ ( UpperCAmelCase_ : int ) -> bool: if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): __lowerCamelCase : Union[str, Any] = F'Input value of [number={number}] must be an integer' ...
13
__lowerCamelCase = """Tobias Carryer""" from time import time class UpperCAmelCase : def __init__(self : Dict , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : str , snake_case__ : Optio...
204
0
"""simple docstring""" def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = len(_snake_case ) + 1 UpperCamelCase = len(_snake_case ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of...
711
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMSche...
544
0
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter UpperCAmelCase__ : Optional[int]...
410
'''simple docstring''' def _lowercase ( UpperCamelCase__ : dict ): __A : Dict = set() # edges = list of graph's edges __A : Any = get_edges(UpperCamelCase__ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and ...
365
0
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTester...
718
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import Tokeniz...
605
0
"""simple docstring""" 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=1337 , num_exampl...
156
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_uti...
156
1
a__ : str = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ...
714
from __future__ import annotations def _lowerCAmelCase ( A__ , A__ ): if b == 0: return (1, 0) ((lowercase__), (lowercase__)) = extended_euclid(A__ , a % b ) lowercase__ = a // b return (y, x - k * y) def _lowerCAmelCase ( A__ , A__...
642
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase = { "configuration_m2m_100": ["M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP", "M2M100Config", "M2M100OnnxConfig"], "tokenization_m2m_100": ["M2...
66
"""simple docstring""" 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_ARCHIV...
308
0
'''simple docstring''' def __UpperCamelCase ( _A , _A = 0 ): lowerCAmelCase_ = length or len(_A ) lowerCAmelCase_ = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: lowerCAmelCase_ , l...
717
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def __UpperCamelCase ( _A ): lowerCAmelCase_ = 384 ...
325
0
from math import factorial, radians def A__( __lowerCAmelCase , __lowerCAmelCase = 18 , __lowerCAmelCase = 10 ): _snake_case : str = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians _snake_case : Dic...
304
from collections import defaultdict def A__( __lowerCAmelCase , __lowerCAmelCase ): _snake_case : str = first_str.lower().strip() _snake_case : Dict = second_str.lower().strip() # Remove whitespace _snake_case : Dict = first_str.repla...
304
1
'''simple docstring''' def _A ( A__ = 1000000 ): """simple docstring""" __lowercase = set(range(3 , A__ , 2 ) ) primes.add(2 ) for p in range(3 , A__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , ...
624
'''simple docstring''' def _A ( A__ = 50 ): """simple docstring""" __lowercase = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): way...
624
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase__ : int = { '''configuration_mega''': ['''MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegaConfig...
8
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __UpperCAmelCase = False ...
90
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { "kssteven/ibert-roberta-b...
713
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class snake_case_ ( ...
370
0
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils i...
149
from __future__ import annotations from collections import namedtuple def snake_case_ ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): __lowercase : str = namedtuple("""result""" , """na...
149
1
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, ...
374
"""simple docstring""" def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ) ->Tuple: """simple docstring""" return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCa...
374
1
import itertools import string from collections.abc import Generator, Iterable def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_): """simple docstring""" snake_case__ : List[str] = iter(UpperCAmelCase_) while True: snake_case__ : Tuple ...
648
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase_: Optional[Any] = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': [...
648
1
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf clas...
501
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 lowerCamelCase ( _lowerCamelCase ): '''simple...
501
1
'''simple docstring''' import json import sys def a_ ( __snake_case : Optional[int] , __snake_case : Any ) -> Any: """simple docstring""" with open(_UpperCamelCase , encoding='''utf-8''' ) as f: lowerCamelCase_ =json.load(_UpperCamelCase ) ...
676
from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class __SCREAMING_SNAKE_CASE ( A__ ): A : int = 'opena...
319
0
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __lowerCAmelCase : int = "." # Internal TensorFlo...
284
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __lowerCAmelCase : Tuple = "\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification}...
284
1
'''simple docstring''' import math import tensorflow as tf from packaging import version def lowerCamelCase ( _snake_case : List[Any] ): '''simple docstring''' lowercase__ = tf.convert_to_tensor(_snake_case ) lowercase__ ...
267
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTes...
267
1
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRC...
307
from maths.prime_factors import prime_factors def UpperCamelCase__ ( UpperCAmelCase ) -> int: """simple docstring""" if not isinstance(UpperCAmelCase , UpperCAmelCase ): _a : Optional[Any] = F'Input value of [number={number}...
307
1
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = [] for i in range(len(_UpperCAmelCase) - pat_len + 1): SCREAMING_SNAKE_CASE = True for j in range(_UpperCAmelCase): ...
73
'''simple docstring''' import operator as op snake_case = '''scaler.pt''' snake_case = '''pytorch_model''' snake_case = '''random_states''' snake_case = '''optimizer''' snake_case = '''scheduler''' snake_case = '''pytorch_model.bin''' snake_case = '''pytorch_model.bin.index.json...
309
0
__UpperCAmelCase = { 0: '''0''', 1: '''1''', 2: '''2''', 3: '''3''', 4: '''4''', 5: '''5''', 6: '''6''', 7: '''7''', 8: '''8''', 9: '''9''', 10: '''a''', 11: '''b''', 12: '''c''', 13: '''d''', 14: '''e''', 15: '''f''', } def A__ ( __lo...
710
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, ...
597
0
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin...
2
def SCREAMING_SNAKE_CASE_ ( _snake_case :int ) -> int: if not isinstance(_snake_case , _snake_case ): raise ValueError('''Input must be an integer''' ) if input_num <= 0: raise ValueError('''Input must be positive''' ) return sum( divisor for divisor i...
2
1
"""simple docstring""" import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_comm...
707
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[Any]=False ): __a : Dict = Omeg...
63
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : int = logging.get_logger(__name__) _UpperCAmelCase : Tuple = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/...
362
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCAmelCase : Tuple = { """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100OnnxConfig"""], ...
362
1
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklear...
292
"""simple docstring""" from __future__ import annotations from collections import Counter from random import random class snake_case__ : def __init__( self : Any ): '''simple docstring''' UpperCAmelCase : List[Any] = {} def __lowerCA...
292
1
import warnings from ..trainer import Trainer from ..utils import logging __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class __magic_name__ ( snake_case ): def __init__( self : Optional[Any] , lowerCamelCase__ : List[Any]=None , **low...
348
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class __magic_name__ ( nn.Module ): ...
348
1
'''simple docstring''' from PIL import Image def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> Image: """simple docstring""" def brightness(__lowerCAmelCase ) -> float: return 128 + level + (c - 128) if not -255.0 <= ...
721
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import l...
219
0
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get...
80
UpperCAmelCase__ = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def a_ () -> None: """simple docstring""" __a : Dict = input("Enter message: " ) __a : Dict = input("Enter key [alphanumeric]: " ) __a : str = ...
351
0
def _lowercase ( lowerCamelCase__ : Any, lowerCamelCase__ : Any ): _a = [1] for i in range(2, lowerCamelCase__ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" _a = [] _a = li...
708
'''simple docstring''' import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, f...
691
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json", } class _...
11
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''xlm-roberta-base...
609
0
'''simple docstring''' from __future__ import annotations from collections import deque class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = [] self.adlist.append( {'value': '', 'ne...
542
'''simple docstring''' 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_comm...
542
1
import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor lowerCAmelCase_ = logging.get_logger(__name__) class snake_case_ ( __A ): '''simple docstring''' def __init__( self : int , *_Uppe...
39
"""simple docstring""" def _UpperCAmelCase ( lowerCamelCase__ ): """simple docstring""" return " ".join( """""".join(word[::-1] ) if len(lowerCamelCase__ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(rev...
644
0
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_commo...
712
"""simple docstring""" import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWith...
422
0