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 gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowercase__ :Dict = False class lowercase ( unittest.TestCase ): pa...
101
from __future__ import annotations import math def __UpperCamelCase ( _A : int , _A : int , _A : bool , _A : list[int] , _A : float ) ->int: """simple docstring""" if depth < 0: raise ValueError("""Depth cannot be less than 0""" ) ...
154
0
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( ...
83
'''simple docstring''' from functools import lru_cache @lru_cache def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> int: '''simple docstring''' if num < 0: raise ValueError('''Number should not be negative.''' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) ...
83
1
"""simple docstring""" 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 lowerCAme...
16
"""simple docstring""" from typing import List import numpy as np def lowercase ( a__ : dict ) -> int: _UpperCamelCase = {key: len(a__ ) for key, value in gen_kwargs.items() if isinstance(a__ , a__ )} if len(set(lists_lengths.values() ) ) > 1: ...
256
0
'''simple docstring''' import argparse import os import re import packaging.version lowerCAmelCase: List[str] = 'examples/' lowerCAmelCase: List[Any] = { 'examples': (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), 'init': (re...
96
'''simple docstring''' import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, Character...
96
1
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...
180
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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices ...
180
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/r...
351
from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX models at https://huggingfac...
167
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCAmelCase (metaclass=__lowerCamelCase ): """simple docstring""" _UpperCAmelCase :Tuple = ['sentencepiece'] def __init__( self , *_UpperCAmelCase , **_UpperCAmelCase ): ...
177
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('>=', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint....
12
0
'''simple docstring''' # Function to print upper half of diamond (pyramid) def _lowerCAmelCase ( lowercase ) -> Dict: for i in range(0 , lowercase ): for _ in range(0 , n - i - 1 ): # printing spaces print(""" """ , end="""""" ) for...
46
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _a : List[str] = """▁""" _a : Optional[int] = {"""vocab_file""...
46
1
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def snake_case_ ( A_ : str = "isbn/0140328726" ): '''simple docstring''' _lowerCamelCase : List[str] = olid.strip().str...
72
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfi...
255
0
'''simple docstring''' from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case =logging.get_logger(__name__) # TODO Update this __snake_case ={ """facebook/esm-1b...
367
'''simple docstring''' def a_ ( lowerCamelCase : list[int] ): if not nums: # Makes sure that the list is not empty raise ValueError('List is empty' ) lowerCAmelCase = sum(lowerCamelCase ) / len(lowerCamelCase ) # Calculate the average return sum(...
55
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize...
24
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stab...
265
0
from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class __a( __A ): """simple docstring...
359
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_...
235
0
"""simple docstring""" import os from datetime import datetime as dt from github import Github A_ = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''enhancement''', '''new pipeline/model''', '''new scheduler''', '''wip''...
64
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import ...
195
0
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from tran...
315
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor __UpperCAmelCase : Optional[int] = logging.get_logger(__name__) class UpperCAmelCase_ ( _a): '''simple docstring''' def __init__( self , ...
315
1
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, A...
259
def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ): # Return True if there is node that has not iterated. UpperCamelCase :Tuple = [False] * len(SCRE...
259
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = { """microsoft/biogpt""": """https://huggingface.co/microsoft/biogpt/resolve/main/con...
157
"""simple docstring""" import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntim...
157
1
"""simple docstring""" import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _SCREAMING_SNAKE_CASE : Tuple = version.parse(importlib_metadata.version('''nltk''')) if NLTK_VERSION >= versi...
183
"""simple docstring""" 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 _SCREAMING_SNAKE_CASE : List[Any] ...
183
1
"""simple docstring""" import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_av...
365
import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict _snake_case : List[str] = namedtuple( "_TestCommandArgs", [ "da...
134
0
import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...
65
from maths.prime_factors import prime_factors def __lowerCamelCase ( UpperCAmelCase_ : int ): """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): a :Dict = F'''Input value of [number={number}] must be an integer'''...
94
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device a_ = False class snake_case ( uni...
365
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", ...
163
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils im...
66
"""simple docstring""" import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def A_ ( _lowercase ): '''simple docstring''' snake_case_ :Union[str, Any] = os.path.join(args.tf_model_dir, """parameters.j...
66
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class a ( metaclass=_a ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = ["torch", "transformers", "onnx"] def __init__( self : int , *snak...
240
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCAmelCase :Union[str, Any] = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], ...
240
1
"""simple docstring""" def a_ ( lowerCamelCase , lowerCamelCase ): return abs(lowerCamelCase ) if a == 0 else greatest_common_divisor(b % a , lowerCamelCase ) def a_ ( lowerCamelCase , lowerCamelCase ): while y: # --> when y=0 then loop w...
98
"""simple docstring""" from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_av...
167
0
'''simple docstring''' import math from collections.abc import Iterator from itertools import takewhile def UpperCamelCase_ ( A__ : Tuple ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 ...
369
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : List[str] = { "configuration_bigbird_pegasus": [ "BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP", "BigBirdPeg...
89
0
'''simple docstring''' from __future__ import annotations from collections.abc import Generator def _A ( ) -> Generator[int, None, None]: _lowercase : List[Any] = {} _lowercase : List[str] = 2 while True: _lowercase : List[str] = factor_ma...
250
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFe...
69
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase : int = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRL...
367
'''simple docstring''' import math class __UpperCAmelCase : '''simple docstring''' def __init__(self : int , _lowerCAmelCase : List[Any]=0 ): # a graph with Node 0,1,...,N-1 A = n A = [ [math.inf for j in range(0 , _lowerCAmelCase )] for i in...
337
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase :List[Any] = { 'configuration_clap': [ 'CLAP_PRETRAINED_MODEL_ARCHIVE_LIST', 'ClapAudioConfig', 'ClapConfig', ...
263
"""simple docstring""" import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_...
263
1
import requests lowerCAmelCase__ : Union[str, Any] ='''''' # <-- Put your OpenWeatherMap appid here! lowerCAmelCase__ : Tuple ='''https://api.openweathermap.org/data/2.5/''' def __lowercase ( a__ = "Chicago" , a__ = APPID ) -> dict: return req...
118
def __lowercase ( a__ = 10_00 ) -> int: __SCREAMING_SNAKE_CASE = -1 __SCREAMING_SNAKE_CASE = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c __SCREAMING_SNAK...
118
1
'''simple docstring''' import qiskit def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) -> qiskit.result.counts.Counts: '''simple docstring''' UpperCAmelCase_ = qiskit.Aer.get_backend("aer_simulator" ) UpperCAmelCase_ ...
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor A = logging.get_logger(__name__) class __lowercase ( _UpperCamelCase ): '''simple docstring''' ...
160
0
def A__ ( lowerCamelCase , lowerCamelCase ) -> int: return int(input_a == input_a == 0 ) def A__ ( ) -> None: print("""Truth Table of NOR Gate:""" ) print("""| Input 1 | Input 2 | Output |""" ) print(F'''| 0 | 0 | {nor_gate(0 ...
370
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : Optional[int] = logging.get_logger(__name__) lowerCamelCase_ : Dict = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-o...
223
0
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCamelCase_ = logging.get_logger('transformers.models.speecht5') def UpperCamelCase ( UpperCAmelCase , Uppe...
243
"""simple docstring""" from __future__ import annotations class snake_case : def __init__( self , __UpperCAmelCase) ->Any: a_ = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same numb...
243
1
def _A ( __magic_name__ , __magic_name__ ): return abs(__magic_name__ ) if a == 0 else greatest_common_divisor(b % a , __magic_name__ ) def _A ( __magic_name__ , __magic_name__ ): while y: # --> when y=0 then loop will terminate and return x as final GCD. lowercase__ , ...
351
import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, R...
201
0
'''simple docstring''' import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, ...
83
"""simple docstring""" import os from datetime import datetime as dt from github import Github _A = [ """good first issue""", """feature request""", """wip""", ] def a__ ( ) -> str: UpperCAmelCase__ : Union[str, Any] = Github(os.environ["""GITHUB_TOKEN"""] ...
171
0
from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils i...
49
import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS loggin...
49
1
'''simple docstring''' import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() __a = logging.get_lo...
145
'''simple docstring''' import heapq as hq import math from collections.abc import Iterator class A__ : """simple docstring""" def __init__( self : Any , lowerCAmelCase__ : Any ) -> Dict: """simple docstring""" _UpperCAmelCase ...
145
1
"""simple docstring""" import qiskit def A ( snake_case :int , snake_case :int ) -> qiskit.result.counts.Counts: __UpperCamelCase = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __UpperCamelCase = qiskit.QuantumCircuit...
358
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import r...
263
0
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available...
62
import socket def _a ( ): """simple docstring""" lowercase__ = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) lowercase__ = socket.gethostname() lowercase__ = 1_23_12 sock.connect((host, port) ) sock.send...
110
0
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCamelCase__: def __init__( self : int , lowerCAmelCase : Collection[float] | None = None )-> None: ...
91
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowerCamelCase__ ( A : int , A : int , A : int , A : int , A : int , A ...
91
1
import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def __UpperCamelCase ( _lowerCAmelCase ) -> Optional[int]: """simple docstring""" if ( (cp >= 0X4e00 and cp <= 0X9fff) or (cp ...
116
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar SCREAMING_SNAKE_CASE_:List[Any] = TypeVar("""KEY""") SCREAMING_SNAKE_CASE_:Dict = TypeVar("""VAL""") @dataclass(frozen=SCREAMING_SNAKE_CASE__ , slo...
116
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase = { """configuration_convnext""": ["""CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvNextConfig""", """C...
267
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase = {"""configuration_vit_msn""": ["""VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMSNConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvai...
267
1
"""simple docstring""" from collections import deque from .hash_table import HashTable class __lowerCamelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self : Dict , *a_ : Optional[int] , **a_ : Dict ): super().__init__(*a_ ...
241
import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py A : Tuple = "src/transformers" A : Optional[Any] = "docs/sour...
118
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCAmelCase_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependen...
356
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
61
0
"""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_common import Backb...
98
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , lowercase : int = 16 , lowercase : int = 88 , l...
282
0
"""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.tes...
314
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case__ : Any = logging.get_logger(__name__) snake_case__ : Any = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve...
314
1
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require...
52
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceF...
52
1
import math def lowerCamelCase_ ( UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] ): """simple docstring""" if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(Upp...
359
import requests __A = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def lowerCamelCase_ ( UpperCamelCase__ : str ) -> None: """simple docstring""" __lowerCamelCase = requests.get(_NEWS_API + bbc_news_api_key ).jso...
348
0
"""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, Cal...
224
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops ...
224
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCamelCase : List[Any] = { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''', '''albert-large-v1''': '''...
356
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel...
306
0
def lowerCAmelCase__ ( lowerCamelCase_ : float): '''simple docstring''' if edge <= 0 or not isinstance(lowerCamelCase_ ,lowerCamelCase_): raise ValueError('''Length must be a positive.''') return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def lowerCAmelCase...
129
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggi...
129
1
from math import asin, atan, cos, radians, sin, sqrt, tan _A = 6_378_137.0 _A = 6_356_752.314_245 _A = 637_8137 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREA...
117
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...
117
1
"""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 A_ (unit...
61
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ ...
130
0
"""simple docstring""" from collections.abc import Callable class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase = None ): '''simple docstring''' lowerCAmelCase__ :list = [] # Stores in...
367
"""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 ..pipel...
254
0
"""simple docstring""" from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands ...
194
"""simple docstring""" import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params...
263
0
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_imag...
360
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging A_ :Union[str, Any] = logging.get_logger(__name__) A_ :Tuple = { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/config.json''', '''x...
245
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _A : Any ={ '''configuration_data2vec_audio''': ['''DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2V...
41
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 1000 ) -> int: lowerCamelCase__ : str = -1 lowerCamelCase__ : Dict = 0 for a in range(1 , n // 3 ): # Solving the tw...
41
1
'''simple docstring''' import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_...
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
class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" pass class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" pass class __lowerCAmelCase : """simple docstring""" ...
90
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin a_ = '\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbo...
249
0
'''simple docstring''' 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 lowerCAmelCase_ : List[Any] ...
361
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmel...
346
0
"""simple docstring""" from __future__ import annotations __lowerCamelCase = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class UpperCamelCase__: def __init_...
221
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_c...
61
0
"""simple docstring""" import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup a_ = logging.get_logger(__name__) cla...
291
"""simple docstring""" a_ = { """meter""": """m""", """kilometer""": """km""", """megametre""": """Mm""", """gigametre""": """Gm""", """terametre""": """Tm""", """petametre""": """Pm""", """exametre""": """Em""", """zettametre""": """Zm""", """yottametre""": """Ym""",...
291
1
"""simple docstring""" def _snake_case ( lowerCamelCase__ : int = 100 ) -> int: lowerCamelCase_ : Dict =set() lowerCamelCase_ : Tuple =0 lowerCamelCase_ : Optional[Any] =n + 1 # maximum limit for a in ra...
144
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING A__ : Optional[Any] = logging...
144
1
from __future__ import annotations from typing import Any class __snake_case : def __init__( self : int , _lowercase : int , _lowercase : int , _lowercase : float = 0 ): """simple docstring""" SCREAMING_SNAKE...
204
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase : Optional[int] = { '''configuration_whisper''': ['''W...
204
1
from __future__ import annotations A__ : List[Any] = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } cl...
103
import argparse import os import re import packaging.version A__ : Dict = '''examples/''' A__ : Any = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^...
103
1
from __future__ import annotations def snake_case__ ( SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' if len(SCREAMING_SNAKE_CASE_ ) == 0: return False lowercase__ : Tuple = len(S...
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 ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dime...
216
0
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # 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 # # ...
27
import enum import shutil import sys UpperCAmelCase, UpperCAmelCase : Union[str, Any] = shutil.get_terminal_size() UpperCAmelCase : Dict = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"} class __lowercase ( enum.Enum ): """simple docstring""" UpperCamel...
252
0
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test...
279
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_xglm''': ['''XGLM_PRETRAINED_...
279
1
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. _UpperCamelCase = 10 def lowerCAmelCase__( lowercase : int , lowercase : int , lowercase ...
326
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) _UpperCamelCase = logging.getLogg...
326
1
from string import ascii_uppercase lowercase__ : List[Any] = {str(ord(c) - 55): c for c in ascii_uppercase} def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase) -> str: if isinstance(__UpperCamelCase , __UpperCamelCase): raise TypeError("int() can't co...
180
lowercase__ : Optional[int] = [ "DownloadConfig", "DownloadManager", "DownloadMode", "StreamingDownloadManager", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
180
1
import argparse import os import re import packaging.version A : Any = '''examples/''' A : List[Any] = { '''examples''': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTI...
6
'''simple docstring''' from ..utils import DummyObject, requires_backends class _lowerCamelCase ( metaclass=lowercase__ ): '''simple docstring''' A_ : Optional[Any] = ["""flax""", """transformers"""] def __init__( self : Union[str, Any] , *_A : ...
331
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_sentence...
177
import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Union[dict, list, tu...
177
1
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_( self ) -> str: lowerCamelCase_ = 10 ...
19
import argparse import hashlib # hashlib is only used inside the Test class import struct class a__ : """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : Optional[int] ) ->str: """simple docstring""" ...
245
0
"""simple docstring""" import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch lowerCam...
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 argparse import ArgumentParser from .env import EnvironmentCommand def lowerCamelCase ( ) -> str: '''simple docstring''' __UpperCAmelCase : List[str] = ArgumentParser("""Diffusers CLI tool""" , usage="""diffuser...
115
"""simple docstring""" 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 Option...
115
1
'''simple docstring''' import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers...
371
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device _SCREAMING_SNAKE_CASE : Any = False class _snake_case ...
92
0
"""simple docstring""" from PIL import Image def snake_case_ ( A_ : Image, A_ : float ): '''simple docstring''' def brightness(A_ : int ) -> float: return 1_28 + level + (c - 1_28) if not -255.0 <= level <= 255.0: ...
72
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase ...
72
1
'''simple docstring''' class _lowerCAmelCase : '''simple docstring''' def __init__(self , UpperCAmelCase ) -> List[Any]: _snake_case = val _snake_case = None _snake_case = None def lowercase (se...
354
'''simple docstring''' import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase = [ 'word_embedding...
270
0
"""simple docstring""" from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelE...
25
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from...
184
0
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowercase ( lowerCAmelCase__ : ...
11
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = { "configuration_vision_text_dual_encoder": ["VisionTextDual...
11
1
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.ut...
21
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) ...
90
0
"""simple docstring""" from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) lowerCAmelCase_ : Optional[int] = 2_9_9_7_9_2_4_5_8 # Symbols lowerCAmelCase_ : Any = symbols('''ct x y z''') def _lowerCAmelCase ( lo...
369
"""simple docstring""" from __future__ import annotations import math def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3...
248
0
'''simple docstring''' import os from distutils.util import strtobool def snake_case_ (_a : Union[str, Any] , _a : List[Any] ): for e in env_keys: UpperCAmelCase = int(os.environ.get(_a , -1 ) ) if val >= 0: return ...
34
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleCh...
34
1
"""simple docstring""" import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization...
320
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, ...
320
1
def lowercase ( SCREAMING_SNAKE_CASE__ : list ) -> list: _snake_case : Any = len(SCREAMING_SNAKE_CASE__ ) for i in range(1 , SCREAMING_SNAKE_CASE__ ): _snake_case : List[Any] = collection[i] _snake_case : Optional[Any] = 0 _snake_case : ...
317
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE_ ) class snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' ...
317
1
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class A__ ( __magic_name__ ): lowercase = [...
369
from ..utils import DummyObject, requires_backends class A__ ( metaclass=__magic_name__ ): lowercase = ['torch', 'transformers', 'onnx'] def __init__( self : Any , *a : Any , **a : Any ): '''simple doc...
307
0
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , a__ ): def lowerCamelCase__ ( self : Optional[int] ): __lowerCamelCase : Any ...
135
def a ( A__ : str , A__ : bool = False ) -> str: """simple docstring""" if not isinstance(A__ , A__ ): _lowercase =F'''Expected string as input, found {type(A__ )}''' raise ValueError(A__ ) if...
205
0
"""simple docstring""" import numpy as np class UpperCAmelCase_ : def __init__( self : List[str] ) -> Optional[int]: _UpperCamelCase = (0, 0) _UpperCamelCase = None _UpperCamelCase = 0 _UpperCamelCase...
366
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy...
54
0
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient SCREAMING_SNAKE_CASE :Tuple = WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def _lowerCAmelCas...
159
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json',...
294
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _SCREAMING_SNAKE_CASE = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_tor...
81
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 from fastapi.routing impor...
81
1
def a_ ( __lowercase : int = 1_000 ) -> int: return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
282
from collections.abc import Sequence def a_ ( __lowercase : Sequence[float] , __lowercase : float ) -> float: return sum(c * (x**i) for i, c in enumerate(__lowercase ) ) def a_ ( __lowercase : Sequence[float] , __lowercase : float ) -> float: ...
282
1
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.uti...
368
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar _lowerCamelCase : Union[str, Any] = TypeVar('''T''') class lowercase ( Generic[T]...
206
0
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCame...
62
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def a_ ...
307
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, lo...
356
'''simple docstring''' import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationT...
135
0
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging _lowerCamelCase : List[str] = """\ """ _lowerCamelCase : List[Any] = """ Perplexity (PPL) is one of th...
14
import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename A__ = '''http://www.mocksite.com/file1.tx...
230
0
"""simple docstring""" from manim import * class lowerCamelCase__ ( __magic_name__ ): '''simple docstring''' def _lowerCAmelCase ( self ) -> int: _lowerCAmelCase =Rectangle(height=0.5 , width=0.5 ) _lowerCAmelCase =Rectan...
357
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class lowerCamelCase__ : '''simple docstring''' lowerCamelCase = None lowerCamelCase = False lowerCamelCase = F...
341
0
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _UpperCAmelCase (UpperCamelCase__ : dict ): return (data["d...
11
from __future__ import annotations def _UpperCAmelCase (UpperCamelCase__ : list[int] , UpperCamelCase__ : list[int] , UpperCamelCase__ : int ): _A : Dict = list(range(len(UpperCamelCase__ ) ) ) _A : Any =...
11
1
from __future__ import annotations import typing from collections import Counter def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__lower...
365
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import ...
325
0
class _A: """simple docstring""" def __init__( self , _A , _A ): __A : Optional[int] = name __A : List[str] = val def __str__( self ): return F"""{self.__class__.__name__}({self.name}, {self.val})""" ...
280
import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=a , default='biencoder-nq-dev.json' ...
280
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case__ : Union[str, Any] = logging.get_logger(__name__) snake_case__ : Any = { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggi...
357
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging snake_case__ : List[str] = logging.get_logger(__name__) class snake_case_( a__ ): ...
314
0
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_pa...
140
from collections import deque from .hash_table import HashTable class UpperCAmelCase ( __A ): '''simple docstring''' def __init__( self , *lowercase , **lowercase ): """simple docstring""" super().__init__(*lowercase , **lowerca...
140
1
"""simple docstring""" from collections import deque class __a : """simple docstring""" def __init__( self : Dict , lowercase_ : str , lowercase_ : int , lowercase_ : int ): UpperCamelCase__ : Any =process_name ...
368
"""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 wo...
157
0