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
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
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { "asapp/sew-tiny-100k": "https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json", # See all SEW models at https://huggingface.co...
231
1
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, OpenAIGPTDoubleHe...
350
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = '''''' for i in table: res += inp[i - 1] return res def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" ...
330
0
"""simple docstring""" import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "vocab_file": "vocab.json", ...
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join(...
45
1
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def __SCREAMING_SNAKE_CASE ( A_ , A_ = True , A_ = math.inf , A_ = -math.inf , A_ = math.inf , A_ = -math.inf , A_ = False , A_ =...
74
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, Li...
74
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
47
from math import isqrt def _lowerCamelCase( lowercase__ ) -> bool: '''simple docstring''' return all(number % divisor != 0 for divisor in range(2 , isqrt(lowercase__ ) + 1 ) ) def _lowerCamelCase( lowercase__ = 1_0**6 ) -> int: '''simple docstring''' __...
295
0
"""simple docstring""" import os _A = {'I': 1, 'V': 5, 'X': 1_0, 'L': 5_0, 'C': 1_0_0, 'D': 5_0_0, 'M': 1_0_0_0} def UpperCAmelCase ( a_ ): '''simple docstring''' lowerCamelCase : int = 0 lowerCamelCase : Dict = 0 while index < ...
362
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _A = logging.get_logger('transformers.models.speecht5') def UpperCAmelCase ( a_, a_, a_ ): ...
205
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer UpperCAmelCase_ = logging.get_logger(__...
201
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, l...
201
1
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel _A = logging.getLogger(__name__) def _Uppe...
366
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset _A = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: ...
117
0
import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_se...
71
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class __a ( __UpperCamelCase ...
196
0
"""simple docstring""" def snake_case ( A__ ): return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(A__ ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__('''doctest''').testmod()
253
"""simple docstring""" import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class UpperCamelCase_ (__A ): __magic_name__ = '''M-CLIP''' def __init__( self : Any , lowerCAmelCase_ : str=1_024 , lowerCAmelCase_ : str=76...
253
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy snake_case__ : Tuple = logging.get_lo...
60
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class SCREAMING_SNAKE_CASE (datasets.BuilderConfig ): lower...
190
0
'''simple docstring''' import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaCo...
370
'''simple docstring''' 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 impo...
129
0
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, DistilBertForMaskedLM, DistilB...
262
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig _UpperCAmelCase : Dict ={ """susnato/ernie-m-base_pytorch""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json""", """susnato/ernie-m-large_pytorch""": """https...
262
1
import qiskit def lowerCamelCase_ ( _a : int , _a : int ): '''simple docstring''' UpperCAmelCase_ : Any = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register UpperCAmelCase_ : Tuple ...
355
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { '''shi-labs/dinat-mini-in1k-224''': '''http...
59
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available snake_case_ = { 'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig'], } try: if not is_torch_avail...
24
"""simple docstring""" def _lowerCAmelCase ( UpperCamelCase_ = 100 ): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__mai...
100
0
"""simple docstring""" import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTest...
365
"""simple docstring""" import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor A__ : str = logging.get_logger(__name__) class lowercase__ ( snake_case__ ): def __init__( self : Optional[Any] , *snak...
209
0
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = (KDPMaDiscreteScheduler,) lo...
7
"""simple docstring""" from __future__ import annotations lowerCamelCase__ = list[tuple[int, int]] lowerCamelCase__ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0...
86
0
"""simple docstring""" import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch...
239
"""simple docstring""" from torch import nn class _SCREAMING_SNAKE_CASE( nn.Module ): def __init__( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) -> List[str]: """simple docstring""" super()...
239
1
"""simple docstring""" from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCamelCase_ ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__...
224
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = ...
54
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" _lowerCamelCase = ["""image_processor""", """tokenizer"""] _lowerCamelCase = """ViTImagePr...
367
"""simple docstring""" from typing import TYPE_CHECKING from ..utils import _LazyModule a_ = { """config""": [ """EXTERNAL_DATA_FORMAT_SIZE_LIMIT""", """OnnxConfig""", """OnnxConfigWithPast""", """OnnxSeq2SeqConfigWithPast""", """PatchingSpec""", ], ...
291
0
"""simple docstring""" import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration a : List[str] = [ # tf -> hf ('''/''', '''.'''), (...
105
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCamelCase : List[Any] = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import w...
47
0
"""simple docstring""" 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 Opti...
11
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[str]] , lowerCAmelCase__ : int , ) -> None: __a ...
11
1
import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase=None ...
124
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...
124
1
"""simple docstring""" import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax impor...
212
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational...
212
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowercase_ = logging.get_logger(__name__) lowercase_ = { 'facebook/convnextv...
266
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import ...
266
1
'''simple docstring''' from typing import Any class A__ : def __init__( self : List[str] , _a : Any ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =data _SCREAMING_SNAKE_CASE =None def __repr...
360
'''simple docstring''' import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class A__ ( A__ ): A__ = 'MCTCTFeatureExtractor' A__ = 'AutoTokenizer' def __init__( self : Optional[Any] , _a : Optional[int] ...
114
0
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) __UpperCAmelCase = { 'sample_size': 32, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 2, 'num_...
29
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def A_ ( ) -> List[Any]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.rais...
52
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 AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def A_ ( _lowerCAmelCase ) -> Tuple: Up...
365
from scipy.stats import spearmanr import datasets __lowerCamelCase : List[str] = """ The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive...
140
0
import math from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Tuple = { '''facebook/data2vec-base-960h''': '''https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json''', ...
138
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 __A : Tuple = logging.get_logger(__name__) __A : List[Any] = R''' Args: input_ids (`torch.LongTensor` o...
138
1
'''simple docstring''' def A (__lowerCamelCase :int = 1000 ): _lowerCAmelCase = 2**power _lowerCAmelCase = str(__lowerCamelCase ) _lowerCAmelCase = list(__lowerCamelCase ) _lowerCAmelCase = 0 for i in list_num: sum_of_num += int...
370
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase = {"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]} try: if not is_torch_available(): ...
229
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _SCREAMING_SNAKE_CASE = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotA...
327
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration _SCREAMING_SNAKE_CASE = 50_00_00 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = os.path.split(__file__) _SCREAMING_SNAKE_CASE ...
327
1
def A ( __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = False while is_sorted is False: # Until all the indices are traversed keep looping UpperCAmelCase_ = True for i in range(0 , l...
363
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, B...
344
0
from __future__ import annotations class SCREAMING_SNAKE_CASE__ : def __init__(self : str , a__ : int = 0 ): """simple docstring""" __snake_case = key def a (self : str , a__ ...
24
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' def __init__( self , _A , _A , _A ): ...
257
0
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.utils import write_basic_c...
169
import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCa...
169
1
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" A__ = args.pruning_method A__ = ar...
14
import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common ...
14
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE) class lowerCamelCase__( __SCREAMING_SNAKE_CASE): UpperCAmelCase__ : str = fi...
361
from math import ceil, sqrt def lowerCamelCase__ ( A__ : int = 1000000 ): '''simple docstring''' __lowerCamelCase = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: __lowerCamelCase ...
29
0
from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging A : Any = logging...
118
'''simple docstring''' import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers...
162
0
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : int ) -> int: '''simple docstring''' return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __UpperCAmelCase ( UpperCAmelCase_ : int ) -> bool: '''simple docstring''' __s...
364
"""simple docstring""" from __future__ import annotations import os from typing import Any import requests _a : int= "https://api.github.com" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user _a : Dict= BASE_URL + "/user" ...
95
0
def lowerCAmelCase_ ( __A ) -> str: '''simple docstring''' UpperCAmelCase__ = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def lowerCAme...
65
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = [ "encoder.version", "dec...
65
1
from __future__ import annotations from typing import Generic, TypeVar __UpperCAmelCase = TypeVar('''T''') class lowerCamelCase__ ( Generic[T] ): def __init__( self : Any , _a : T ): a__: List[str] =data a__: List[Any] ...
354
import os import unicodedata 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 SPIECE_UNDERLINE, logging __UpperCAmelCase = logging.get_logger(__name__) _...
42
0
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from tra...
313
from abc import ABC, abstractmethod from typing import List, Optional class a_ ( a__ ): """simple docstring""" def __init__( self ) ->List[str]: # test for the above condition self.test() def __lowerCAmelCase ( self ...
313
1
"""simple docstring""" from math import factorial lowerCAmelCase : Any = {str(d): factorial(d) for d in range(10)} def a__ ( snake_case__ ) -> int: return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def a__ ( ) -> int: lowerCa...
168
"""simple docstring""" import argparse import math import traceback import dateutil.parser as date_parser import requests def a__ ( snake_case__ ) -> Optional[Any]: lowerCamelCase = {} lowerCamelCase = job["""started_at"""] lowerCamelCase = job["""comple...
168
1
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('''repo_id''' , ['''canonical_dataset_name''', '''org-name/dataset-name'''] ) @pytest.mark.parametrize('''path''' , ['''filename.csv''', '''filename with blanks.csv'''] ) @pytest....
338
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase__ : Any = logging.get_logger(__name__) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ...
121
0
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterM...
363
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_m...
149
0
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils imp...
301
"""simple docstring""" from __future__ import annotations from statistics import mean def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = [0] * no_of_processes __lowerCAmelCase = [0] * no_of_processes # Initializ...
301
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase :List[Any] = {} try: if not is_sentencepiece_available()...
361
'''simple docstring''' def a ( lowerCamelCase__ ): '''simple docstring''' return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
135
0
import requests def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> None: """simple docstring""" A : Any = {"""Content-Type""": """application/json"""} A : str = requests.post(_lowerCAmelCase , json={"""text""": message...
116
from __future__ import annotations from math import ceil, floor, sqrt def __UpperCamelCase ( _lowerCAmelCase = 200_0000 ) -> int: """simple docstring""" A : list[int] = [0] A : int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): ...
116
1
'''simple docstring''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging _lowerCAmelCase = ...
98
'''simple docstring''' from __future__ import annotations from fractions import Fraction def UpperCamelCase ( a , a ) -> bool: '''simple docstring''' return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def Up...
98
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A = 1_000 ) -> int: """simple docstring""" return sum(e for e in range(3 , A ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f"""{solution() = }""")
2
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : ...
270
0
lowercase : Union[str, Any] = 0 # The first color of the flag. lowercase : int = 1 # The second color of the flag. lowercase : int = 2 # The third color of the flag. lowercase : Tuple = (red, white, blue) def ...
36
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' A : Tuple = ['image_processor', 'tokenizer'] A : Tuple = 'AutoIm...
36
1
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency _lowercase: Optional[Any] = { "E": 12.70, "T": 9.06, "A": 8.17, "O": 7.51, "I": 6.97, "N": 6.75, "S": 6.33, "H": 6.09, "R": 5.99, "D": 4.25, "L": 4.03, "C": 2.78, "U": 2....
227
from __future__ import annotations from typing import Any def snake_case( __magic_name__ ) -> None: '''simple docstring''' create_state_space_tree(__magic_name__ , [] , 0 ) def snake_case( __magic_name__ , __magic_name__ , ...
308
0
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis...
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
"""simple docstring""" import torch def _SCREAMING_SNAKE_CASE ( ) ->Optional[Any]: '''simple docstring''' if torch.cuda.is_available(): a : List[Any] = torch.cuda.device_count() else: a : Any = 0 print(F"""Successfully ran ...
105
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A ...
10
0
"""simple docstring""" from __future__ import annotations a : Optional[Any] = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def _SCREAMING_SNAKE_CASE ( _lowercase : list[list[int]] , _lowercase :...
79
"""simple docstring""" import math def _SCREAMING_SNAKE_CASE ( _lowercase : int = 100 ) ->int: '''simple docstring''' a : Dict = sum(i * i for i in range(1 , n + 1 ) ) a : Tuple = int(math.pow(sum(range(1 , n + 1...
79
1
"""simple docstring""" from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class snake_case ( lowerCamelCase_ ): SCREAMING_SNAKE_CASE_ : Dict = """philschmid/bart-large-cnn-samsum""" SCREAMING_SNAKE_CASE_ : int ...
217
"""simple docstring""" def lowercase (SCREAMING_SNAKE_CASE_ : int = 10_00 ) -> int: SCREAMING_SNAKE_CASE = 2**power SCREAMING_SNAKE_CASE = 0 while n: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ...
113
0
'''simple docstring''' import numpy as np a : str = [ ['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z'], ] class a : def __init__( self : Dict ): snake_case_ ...
72
'''simple docstring''' import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class a ( unittest.TestCase ): def A_ ( self : List[Any] ): snake_case_ = [ '''safety_checker/pytorch_model.bin''', ...
72
1
import baseaa def lowerCamelCase_ ( UpperCamelCase__ : str ) -> bytes: """simple docstring""" return baseaa.aaaencode(string.encode('utf-8' ) ) def lowerCamelCase_ ( UpperCamelCase__ : bytes ...
90
from math import pi, sqrt, tan def lowerCamelCase_ ( UpperCamelCase__ : float ) -> float: """simple docstring""" if side_length < 0: raise ValueError('surface_area_cube() only accepts non-negative values' ) return 6 * s...
90
1
"""simple docstring""" SCREAMING_SNAKE_CASE__ : int = [0, 2, 4, 6, 8] SCREAMING_SNAKE_CASE__ : Dict = [1, 3, 5, 7, 9] def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : list[int] , __lower...
351
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, Fl...
339
0
'''simple docstring''' import requests def __a ( UpperCAmelCase , UpperCAmelCase ) ->None: """simple docstring""" A = {"""Content-Type""": """application/json"""} A = requests.post(UpperCAmelCase , json={"""text""": message_body} , head...
258
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / densit...
258
1
'''simple docstring''' import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state i...
25
'''simple docstring''' import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subpr...
25
1
from copy import deepcopy class lowercase__ : '''simple docstring''' def __init__( self, __magic_name__ = None, __magic_name__ = None ) -> None: """simple docstring""" if arr is None and size is not None: UpperCam...
201
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils imp...
201
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) __SCREAMING_SNAKE_CASE ={ "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_M...
351
"""simple docstring""" 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, TensorFlow...
321
0
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def A_ ( _lowerCAmelCase : int, _lowerCAmelCase : List[Any], ...
320
"""simple docstring""" 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 ...
320
1
"""simple docstring""" import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class __lowercase ( _Up...
188
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar A = TypeVar('''T''') class __lowercase ( Generic[T] ): '''simple docstring''' __low...
188
1
'''simple docstring''' import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_on...
85
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in ...
85
1
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class lowerCamelCase_ ( _A ): '''simple docstring''' def __init__( self : ...
256
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ...
256
1
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, O...
233
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_inf...
233
1
"""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 UpperCamelCase : @property de...
95
"""simple docstring""" import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class UpperCamelCase ( lowercase ): @require_torch def _lowercase (self...
95
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available _UpperCamelCase = {"tokenization_herbert": ["HerbertTokenizer"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: p...
275
def _lowercase ( lowercase__ , lowercase__ ): if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCAmelCase : int = str(bin(lowercase__ ) )[2:] # remove the leading "0b" __lowerCAmelCase : Any...
275
1
'''simple docstring''' # Function to print upper half of diamond (pyramid) def __lowerCamelCase ( __snake_case : Optional[int] ) -> Optional[int]: """simple docstring""" for i in range(0, lowerCAmelCase__ ): for _ in range(0, n - i - 1 ): # printing s...
359
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( __snake_case : list[int] ) -> bool: """simple docstring""" return len(set(__snake_case ) ) == len(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
136
0
from collections import defaultdict def lowercase_ ( _A : int ): """simple docstring""" lowerCamelCase__ : Union[str, Any] = 1 lowerCamelCase__ : Dict = True for v in tree[start]: if v not in visited: ret +=...
184
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A : Union[str, Any] = logging.get_logger(__name__) A : Optional[Any] = { "xlm-roberta-base": "...
184
1
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOC...
350
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case__ (ctypes.Structure ): """simple docstring""" __lowerCAmelCase :Dict = [("size", c...
266
0
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE = 3 ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError('number of qubi...
195
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { ...
195
1
# using dfs for finding eulerian path traversal def lowerCamelCase__ ( _lowercase , _lowercase , _lowercase , _lowercase=None ) -> List[str]: '''simple docstring''' UpperCAmelCase_ : Dict = (path or []) + [u] for v in graph...
353
from math import ceil def lowerCamelCase__ ( _lowercase = 1001 ): '''simple docstring''' UpperCAmelCase_ : Optional[Any] = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): UpperCAmelCase_ : List[Any] = 2 * i +...
235
0
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 TokenizerTesterMixin @require_tokenizers class _SC...
38
'''simple docstring''' # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase): __lowerCAmelCase = { '''en''': '''Machine learning is great, isn\'t it?''', '''ru''': '''...
174
0
'''simple docstring''' import argparse a_ : int = """docs/source/_static/js/custom.js""" def a_ ( __snake_case : Tuple ) -> List[str]: """simple docstring""" with open(__snake_case , encoding='''utf-8''' , newline='''\n...
6
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a_ : Any = { """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE...
6
1
'''simple docstring''' import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class lowercase_ ( unittest.TestCase ): def __a ( self ): ...
80
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase_ = {"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]} try: ...
309
0
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from...
56
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: return number | (1 << position) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: return number & ~(1 << position) def _lowercase ( __lower...
56
1
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def A_ ( _lowercase = "isbn/0140328726" ): '''simple docstring''' snake_case_ :str = olid.strip().strip("""/""" ) # Remove leading/trailing whitespace & s...
66
'''simple docstring''' from scipy.stats import spearmanr import datasets lowerCamelCase = """ The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation....
166
0
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Option...
49
import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py __A : Union[str, Any] = 'src/diffusers' # Matches is_xxx_available() __A : Dict = re.compile(R'is\_([a-z_]*)_available\(\...
49
1
from jiwer import compute_measures import datasets _SCREAMING_SNAKE_CASE = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluatio...
180
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor _A = logging.get_logger(__name__) class A ( __UpperCAmelCase ): def __init__( self, *UpperCamelCase__, **UpperCamelCase__ ): """simple docstring""" warnings.warn...
278
0
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWit...
28
from __future__ import annotations from typing import Any class __a : def __init__( self : Dict , UpperCAmelCase : int = 6 ): lowerCAmelCase_ : Node | None = None lowerCAmelCase_ : Node | None = None self....
28
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a_ = logging.get_logger(__name__) a_ = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } ...
152
'''simple docstring''' import unittest import numpy as np import requests 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...
47
0
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput UpperCamelCase__ = "scheduler_config.json" class __SCREAMING_SNAKE_CASE ( _a ...
360
import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, 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 impor...
87
0
"""simple docstring""" import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class snake_case ( SCREAMING_SNAKE_CASE_ ): # to overwrite at featu...
243
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: lowerCAmelCas...
212
0
'''simple docstring''' from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException fro...
371
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=SCREAMING_SNAKE_CASE__): _lowerCamelCase : str = ['torch', 'scipy'] def __init__( self : List[str], *a_ : Optional[int], **a_ : int ): """simpl...
31
0
'''simple docstring''' import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class lowercase ( ...
97
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase: List[Any] = logging.get_logger(__name__) _UpperCamelCase: int = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert ...
255
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A : List[Any] = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTO...
360
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, lo...
323
0
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_...
105
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 transformer...
322
0
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[list[int | float]] ) -> Optional[int]: UpperCAmelCase_ = len(__UpperCamelCase ) UpperCAmelCase_ = len(matrix[0] ) UpperCAmelCase_ = min(__UpperCamelCase , __UpperCamelCas...
369
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : float , __UpperCamelCase : float ) -> float: if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) ...
177
0
'''simple docstring''' from __future__ import annotations __SCREAMING_SNAKE_CASE : Optional[int] = list[list[int]] # assigning initial values to the grid __SCREAMING_SNAKE_CASE : 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,...
31
def __SCREAMING_SNAKE_CASE ( snake_case_ = 1000 ): '''simple docstring''' _UpperCAmelCase = 2**power _UpperCAmelCase = 0 while n: _UpperCAmelCase , _UpperCAmelCase = r + n % 10, n // 10 return r if _...
133
0
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester f...
370
"""simple docstring""" import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state imp...
24
0
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A : str = logging.get_logger(__name__) A ...
305
import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transfor...
305
1
"""simple docstring""" class A__ : def __init__( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = size __lowerCAmelCase : str = [0] * size __lowerCAmelCase : Any = [0] * size @staticmethod def ...
182
"""simple docstring""" 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, TensorFlo...
182
1
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class A_ ( __lowerCamelCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2"...
195
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging UpperCAmelCase = logging.get_logger(__name__) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ): lowercase = r'\w+[.]\d+' ...
195
1
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from...
243
'''simple docstring''' from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = { 'nielsr/canine-s'...
243
1
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTR...
287
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ """camembert-base""": """https://huggingface.co/camembert...
287
1
"""simple docstring""" import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffuse...
359
"""simple docstring""" from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .m...
241
0
"""simple docstring""" from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: ...
66
"""simple docstring""" import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import fr...
290
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class _A ( metaclass=__lowercase ): lowercase__: int = ['''speech'''] def __init__( self : Tuple , *__magic_name__ : List[Any] , **__magic_name__ : Dict...
13
'''simple docstring''' def _a ( _lowerCamelCase ) -> bool: """simple docstring""" __snake_case : Optional[int] = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def _a ( _lowerCamelCase = 5000 ) -> ...
13
1