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
'''simple docstring''' import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditiona...
134
'''simple docstring''' from __future__ import annotations from collections.abc import MutableSequence class lowerCamelCase : '''simple docstring''' def __init__( self : List[str] , lowerCAmelCase_ : int , lowerCAmelCase_ : MutableSequence[float] ) ->...
134
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : Optional[int] = { '''edbeeching/decision-transformer-gym-hopper-medium''': ( '''https://huggingface.co/edbeeching/decis...
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', ...
0
0
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> str: if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise ValueError('iterations must be defined as integers' ) if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not number >= 1: rais...
21
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCAmelCase : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCAmelCase ...
95
0
"""simple docstring""" import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.me...
354
"""simple docstring""" from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def _snake_case ( lowercase__ : bool = True , *lowercase__ : Optional[int] , **lowercase__ : s...
1
0
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0...
54
from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=__snake_case ): '''simple docstring''' A__ : Tuple = ["flax"] def __init__( self: str ,*lowerCamelCase_: int ,**lowerCamelCase_: List[str] ) -> str: requires...
345
0
from __future__ import annotations import pandas as pd def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [0] * no_of_processes SCREAMING_SNAKE_CASE_ = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in ...
363
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, Bit...
257
0
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get...
284
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, re...
284
1
"""simple docstring""" def _lowerCAmelCase ( UpperCamelCase_ ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError("""Input series is not valid, valid series - [2, 4, 6]""" ) if len(__lowerCAmelCase ) == 0: raise ValueError("""Input list must be a non...
353
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/mic...
255
0
import math from numpy import inf from scipy.integrate import quad def _a ( UpperCamelCase_ : float ) -> float: """simple docstring""" if num <= 0: raise ValueError("math domain error" ) return quad(UpperCamelCase_ , 0 , Upp...
340
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils i...
340
1
'''simple docstring''' import inspect import unittest from transformers import ConvNextConfig 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_backbone_c...
246
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase_ = { "configuration_mobilebert": [ "MOBI...
246
1
import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL lowerCAmelCase__ : List[Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def UpperCamelCase__ ...
143
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase__ : str = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S ...
143
1
"""simple docstring""" import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def a__ ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Optional[int] , SCREAM...
133
"""simple docstring""" def a__ ( SCREAMING_SNAKE_CASE : list[int] ): '''simple docstring''' lowerCAmelCase : str = len(SCREAMING_SNAKE_CASE ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(i + 1 , SCREAMING_SNAKE_CASE ): if nu...
133
1
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE...
46
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def lowercase ( _SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' _UpperCAmel...
260
0
"""simple docstring""" import torch def _snake_case ( ) -> Union[str, Any]: if torch.cuda.is_available(): lowerCamelCase_ : int =torch.cuda.device_count() else: lowerCamelCase_ : List[str] =0 print(F"""Successfully ...
209
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( Autoe...
209
1
class lowerCamelCase__ : def __init__(self , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None ) -> Dict: _lowercase =data _lowercase =previous _lowercase =next_node def __str__(self ) -> ...
5
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __UpperCamelCase : Dict = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def ...
146
0
"""simple docstring""" import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class _UpperCamelCa...
259
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: ...
259
1
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) # TODO Update this __A : Optional[Any] = { """facebook/esm-1b""": """https:/...
138
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
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE : Optional[int] = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltC...
360
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE : str = logging.getLogger() def ...
84
0
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 DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity...
222
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _UpperCAmelCase : List[Any] = logging.get_logger(__name__) _UpperCAmelCase ...
222
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = {} class lowerCamelCase (__lowerCamelCase ): """simple ...
191
import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class lowerCamelCase : """simple docstring""" ...
191
1
'''simple docstring''' import os import sys import unittest __snake_case = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_mod...
97
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable __A : List[Any] = { 'configuration_gpt_neox_japanese': ['GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXJapaneseConfig'], 'tokenization_gpt_n...
154
0
'''simple docstring''' import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_visio...
359
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Tuple = { 'configuration_distilbert': [ '...
294
0
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def SCREAMING_SNAKE_CASE__ ( __a ): snake_case_ : int = prime_factors(__a ) if is_square_free(__a ): return -1 if len(__a ) % 2 else 1 return 0 if __name...
327
import re import string import numpy as np import datasets _SCREAMING_SNAKE_CASE = """ Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. """ _SCREAMING_SNAKE_CASE = """ ...
327
1
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available ...
56
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0] * len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Any = [1] * len(__lowerCAmelCase ...
56
1
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, ...
277
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets lowercase : str = """\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex and Sing...
20
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : Union[str, Any] = { "configuration_bigbird_pegasus": [ "BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP", "BigBirdPegasusConfig", "BigBirdPe...
366
def A_ ( A__ , A__ , A__ ) -> 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 years_to_repay <= 0 or not isinstance(A__ , A__ ): ...
225
0
"""simple docstring""" import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionC...
347
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't ...
347
1
"""simple docstring""" import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_availab...
351
"""simple docstring""" from collections.abc import Generator from math import sin def UpperCAmelCase__ (snake_case__ : bytes ): """simple docstring""" if len(snake_case__ ) != 32: raise ValueError("""Input must be of length 32""" ) _snake_case : Optional[int] ...
132
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _a = logging.get_logger(__name__) _a = { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/config.json''', '''funnel-transformer/small-base''': ''...
39
class __lowerCamelCase : """simple docstring""" def __init__( self , UpperCAmelCase = "" , UpperCAmelCase = False ): """simple docstring""" _UpperCAmelCase = {} # A node will be a leaf if the tree contai...
39
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_...
173
import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() __a = logging.get_logger(__name__) def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamel...
173
1
'''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 PreTrainedTokenizer...
56
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class l...
267
0
'''simple docstring''' from importlib import import_module from .logging import get_logger __a = get_logger(__name__) class A__ : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : O...
17
'''simple docstring''' import baseaa def __UpperCAmelCase ( a_: str ): return baseaa.baaencode(string.encode("utf-8" ) ) def __UpperCAmelCase ( a_: bytes ): return baseaa.baadecode(a_ ).decode("utf-8" ) if __name__ == "__main__": ...
17
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils impor...
256
'''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
0
'''simple docstring''' from argparse import ArgumentParser from .env import EnvironmentCommand def _A ( ): """simple docstring""" __lowercase = ArgumentParser('''Diffusers CLI tool''' , usage='''diffusers-cli <command> [<args>]''' ) __lowercase = parser.add_s...
52
'''simple docstring''' def _A ( A__ = 1000 ): """simple docstring""" __lowercase , __lowercase = 1, 1 __lowercase = 2 while True: __lowercase = 0 __lowercase = fa + fa __lowercase , __lowercase = fa, f index += 1 for _...
52
1
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. __snake_case = 2_0_0 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must...
310
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 __lowerCamelCase (_a , unittest.TestCa...
310
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline 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...
52
'''simple docstring''' import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor lowerCAmelCase__ = logging.get_logger(__name__) class lowercase_ (lowerCamelCase__ ): """simple docstring""" def __init__( self : Lis...
52
1
'''simple docstring''' class a_ : '''simple docstring''' def __init__( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = name _SCREAMING_SNAKE_CASE = val def __str__( self ) -> Dict: return f'{self.__class__.__name__}({self....
58
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging...
51
0
'''simple docstring''' import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset...
31
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin ...
31
1
'''simple docstring''' from cva import destroyAllWindows, imread, imshow, waitKey def __snake_case ( UpperCAmelCase_ : Any ): # getting number of pixels in the image lowerCamelCase_ ,lowerCamelCase_ = img.shape[0], img.shape[1] # converting each pixel's color to its...
55
'''simple docstring''' from __future__ import annotations def __snake_case ( UpperCAmelCase_ : int ): lowerCamelCase_ = 2 lowerCamelCase_ = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(UpperCAmelCase_ ) if n > 1: fac...
55
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A = logging.get_logger(__name__) A = { '''uw-madison/mra-base-512-4''': '''https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json''', } ...
358
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_ima...
188
0
"""simple docstring""" from __future__ import annotations def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Tuple = [True] * limit SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int ...
25
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_as...
180
0
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = hex_num.strip() if not hex_num: raise ValueError("No value was passed to the function" ) UpperCamelCase_ = hex_num[0] == "-" if is_negative: Up...
359
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: for param in module.parameters(): UpperCamelCase_ = False def lowerCAmelCase_ ( ) -> Dict: UpperCamelCa...
328
0
from __future__ import annotations __a = 1.6021E-19 # units = C def a ( snake_case__: float , snake_case__: float , snake_case__: float , ): '''simple docstring''' if (conductivity, electron_conc, mobility).count(0 ) != 1: ...
30
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a : Tuple = { 'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP'...
56
0
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py UpperCamelCase : Any = "." if __name__ == "__main__": UpperCamelCase : Optional[int] = os.path.join(REPO_PATH, "utils/document...
366
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import ...
263
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
50
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_comm...
50
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int: return x if y == 0 else greatest_common_divisor(_UpperCAmelCase ,x % y ) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> ...
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True ...
0
1
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) __A : int = { '''sample_size''': 32, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''...
138
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast __A : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __A ( datasets.Bui...
138
1
import argparse import math import traceback import dateutil.parser as date_parser import requests def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : Tuple = {} SCREAMING_SNAKE_CASE_ : Any = job['started_at'] SCREAMING_SNAKE_CASE_ :...
358
from __future__ import annotations def a__ ( A__ ): return len(set(A__ ) ) == len(A__ ) if __name__ == "__main__": import doctest doctest.testmod()
162
0
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environmen...
210
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer __a : List[Any] = logging.getLogger(__name__) def UpperCAmelCase ( ): """simple docstring""" __lowercase = argparse.ArgumentParser( ...
210
1
def __lowerCamelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : str ): """simple docstring""" if not (isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ )): raise ValueError('''longest_common...
352
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) snake_case : Any = pytest.mark.integration @pytest.mark.parametrize('''path''' , ['''paws''', ''...
281
0
'''simple docstring''' import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : str = {name: getatt...
47
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> bool: return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(__UpperCamelCase ) ) def ...
321
0
'''simple docstring''' 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.to...
31
'''simple docstring''' def SCREAMING_SNAKE_CASE__( _UpperCamelCase : list ) -> float: '''simple docstring''' UpperCamelCase__ = 0 while len(_UpperCamelCase ) > 1: UpperCamelCase__ = 0 # Consider two files with minimum cost to be me...
31
1
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 :int = logging.get_logger(__name__) __snake_case :Optional[Any] =...
49
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """c...
293
0
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.u...
233
"""simple docstring""" import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_uti...
233
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) ...
33
"""simple docstring""" def lowercase ( __snake_case : int = 1_0_0_0 ): lowercase_ , lowercase_ : str = 1, 1 lowercase_ : List[str] = 2 while True: lowercase_ : Tuple = 0 lowercase_ : List[Any] = ...
33
1
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class SCREAMING_SNAKE_CASE__ ( snake_case__ ): """simple docstring""" SCREAMING_SNAKE_CASE = '''M-CLIP''' def __init__( self : List[str] ,...
368
'''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 import load_flax_weights_in_pytorc...
37
0
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar _snake_case = TypeVar('KEY') _snake_case = TypeVar('VAL') @dataclass(frozen=snake_case_ , slots=snake_cas...
294
"""simple docstring""" import cva import numpy as np class UpperCamelCase : def __init__( self : Optional[int] , UpperCAmelCase__ : float , UpperCAmelCase__ : int ) -> Dict: if k in (0.0_4, 0.0_6): ...
294
1
"""simple docstring""" from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
365
import baseaa def SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> bytes: return baseaa.baaencode(string.encode('''utf-8''' ) ) def SCREAMING_SNAKE_CASE ( __UpperCamelCase : bytes ) -> str: return baseaa.baadecode(__UpperCam...
177
0
from __future__ import annotations def lowerCamelCase__ ( __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] ): if days_between_payments <= 0: raise ValueError("""days_between_payments must be > 0""" )...
114
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, to...
248
0
import os import numpy import onnx def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: __lowerCamelCase : List[Any] = a.name __lowerCamelCase : Union[str, Any] = b.name __lowerCamelCase : str = '' __lowerC...
113
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a ={ """configuration_roformer""": ["""ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Ro...
113
1
"""simple docstring""" from collections import defaultdict def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = 1 __A = True for v in tree[start]: if v not in visited: ret += dfs(__UpperCamelCase ) if ret % 2 == 0: cuts.append(__...
266
"""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 To...
266
1
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, tor...
256
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, O...
256
1
"""simple docstring""" def __lowercase ( snake_case_ : Optional[Any] ) ->Union[str, Any]: '''simple docstring''' __A : int = 0 __A : List[Any] = len(snake_case_ ) for i in range(n - 1 ): for j in range(i + 1 ,s...
179
"""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...
179
1
'''simple docstring''' import sys def a ( lowerCamelCase__ ): '''simple docstring''' A_ : Optional[Any] = len(lowerCamelCase__ ) A_ : Union[str, Any] = [[0 for x in range(lowerCamelCase__ )] for x in range(lowerCamelCase__ )] A_ : ...
135
'''simple docstring''' import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class _lowerCAmelCase : @property def _a (self...
135
1
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _UpperCAmelCase ( unittest.TestCase ): """simple docstr...
284
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 import Dataset from tr...
225
0
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowerCamelCase ( UpperCAmelCase__ : NDArray[floataa] , UpperCAmelCase__ : NDArray[floataa] , UpperCAmelCase__ : list[int] , UpperCAmelCase_...
21
'''simple docstring''' import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class __magic_name__ ( ctypes.Structure): # _fields is a specific attr expected by ctypes UpperCamelCase__ ...
21
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, Di...
5
from typing import Any def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) -> list: """simple docstring""" _validation( __snake_case , __snake_case , __snake_case , ...
5
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """...
354
'''simple docstring''' from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def a__ ( ) -> tuple[list[int], int]: """simple docstring""" UpperCAmelCase_ : Tuple = [randint(-10_00 ...
67
0
import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class _lowerCAmelCase ( tf.keras.optimizers.schedules.LearningRateSchedule ): d...
231
from __future__ import annotations import math def lowerCAmelCase_ ( _lowercase : int) -> 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: # Negati...
170
0
import argparse import copy def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} with open(_UpperCAmelCase) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE = [] _list.append([line.split()[1...
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decode...
327
0
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from .....
131
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[int] ): UpperCamelCase :Tuple = len(SCREAMING_SNAKE_CASE__ ) print('''The following activities are selected:''' ) # The first activity is always selected UpperCamelCase ...
259
0
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class A__ ( ctypes.Structure ): # _fields is a specific attr expected by ctypes lowercase =...
368
import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import U...
307
0
'''simple docstring''' import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class lowerCAmelCase__ ( tf.keras.optimi...
234
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(...
234
1
"""simple docstring""" import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def A (*__A : str ) -> Optional[int]: """simple docstring""" if not isinstance(a_ , a_...
366
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments ...
7
0
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowercase_ ( _lowerCamelCase : bool = True , *_lowerCamelCase : int , **_lowerCamelCase : Optional[Any]): if not is...
87
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = R''' Args: input_ids (`torch.LongT...
87
1
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 : List[Any] = { """configuration_owlvit...
352
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageRes...
286
0
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline UpperCAmelCase_ : str = datasets.utils.loggi...
38
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.du...
38
1
from math import pi, sqrt def snake_case_ ( lowerCAmelCase_ )-> float: '''simple docstring''' if num <= 0: raise ValueError("""math domain error""" ) if num > 171.5: raise OverflowError("""math range error""" ) elif num - int(lowerCAmelCa...
365
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowercase : """simple docstring""" UpperCAmelCase = 42 UpperCAmelCase = 42 class ...
349
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> int: assert ( isinstance(__lowercase , __lowercase ) and number_of_steps > 0 ), F"""number_of_steps needs to be positive integer, your input {number_of_steps}""" if number_of_s...
319
'''simple docstring''' from __future__ import annotations import math def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list: if len(__lowercase ) != 2 or len(a[0] ) != 2 or len(__lowercase ) != 2 or len(b[0] ) != 2: raise Excepti...
319
1
"""simple docstring""" __A : Optional[Any] = { 'Pillow': 'Pillow', 'accelerate': 'accelerate>=0.11.0', 'compel': 'compel==0.1.8', 'black': 'black~=23.1', 'datasets': 'datasets', 'filelock': 'filelock', 'flax': 'flax>=0.4.1', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', ...
57
"""simple docstring""" import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase_...
57
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _UpperCamelCase ( __A , __A , __A , __A ) -> str: '''simple docstring''' UpperCamelCase__ = s.r...
80
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: ...
80
1
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_image_...
71
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...
71
1
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": a_ = argparse.ArgumentParser( description=( 'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned' ' Distillatio...
175
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from dataset...
175
1
lowercase__ : List[Any] = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p"...
358
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(UpperCamelCase__ ) , """Tato...
180
0
from math import sqrt def lowerCAmelCase_ ( _lowercase : Tuple) -> int: """simple docstring""" a__ : str = 0 for i in range(1 , int(sqrt(_lowercase) + 1)): if n % i == 0 and i != sqrt(_lowercase): total += i + n // i...
170
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, ...
171
0
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, ...
351
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() __lowerCamelCase : Dict = logging.get_logger("""transformers.models.speecht5""") def A_ ( _lowerCAmelCase , _lowerCAmelCase ...
140
0
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class a_...
68
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu lowerCAmelCase__ = get_tests_dir(...
68
1
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __A ( ...
323
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(): import torch i...
323
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase : Any = { 'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'], 'configuration_data2vec...
107
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''camembert-base'...
97
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class _UpperCAmelCase ( unittest.TestCase )...
68
"""simple docstring""" import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ....
68
1
"""simple docstring""" # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the ...
288
import pprint import requests UpperCAmelCase = '''https://zenquotes.io/api''' def UpperCAmelCase_ ( ): return requests.get(API_ENDPOINT_URL + '/today' ).json() def UpperCAmelCase_ ( ): return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ ...
195
0
import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswerin...
366
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Tuple = { '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config....
218
0
from math import isclose, sqrt def a_ ( _A , _A , _A ) -> tuple[float, float, float]: """simple docstring""" snake_case__ = point_y / 4 / point_x snake_case__ = 2 * normal_gradient / (1 + normal_gradient * normal_...
307
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch clas...
307
1
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, ftp_get, ftp_head, get_...
368
from __future__ import annotations def A ( lowercase , lowercase ) -> tuple[int, int]: '''simple docstring''' if b == 0: return (1, 0) ((UpperCamelCase) , (UpperCamelCase)) = extended_euclid(lowercase , a % b ) UpperCamelCase = a // b return (y, x - k ...
110
0
"""simple docstring""" from string import ascii_uppercase _a = {str(ord(c) - 55): c for c in ascii_uppercase} def __a ( __lowerCamelCase, __lowerCamelCase ): if isinstance(__lowerCamelCase, __lowerCamelCase ): raise TypeError("int() can't convert non-string with explicit b...
61
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before token...
240
0
from __future__ import annotations from statistics import mean def __lowerCAmelCase ( a__ , a__ , a__ ) -> list[int]: __a = [0] * no_of_processes __a = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(_...
371
from typing import List from .keymap import KEYMAP, get_character def __lowerCAmelCase ( a__ ) -> List[str]: def decorator(a__ ): __a = getattr(a__ , '''handle_key''' , [] ) handle += [key] setattr(a__ , '''handle_key''' , a__ ...
33
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_ima...
160
"""simple docstring""" from statistics import mean import numpy as np def __A ( a_ :list , a_ :list , a_ :list , a_ :int) -> list: __a : Any = 0 # Number of processes finished __a : Union[str, Any] = ...
160
1
'''simple docstring''' import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common im...
311
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A ( __snake_cas...
311
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase__ = { "configuration_nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"], } try: if not is_torch_available(): ...
339
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration UpperCAmelCase__ = { "tiny.en": "https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32acce...
339
1
'''simple docstring''' import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelC...
356
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _lowerCAmelCase = 10 def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase...
184
0