code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class lowercase_ ( pl.LightningModule ): '''simple docstring''' def __init__( self : Optiona...
315
"""simple docstring""" from collections.abc import Sequence def _A ( UpperCamelCase_ : Sequence[float], UpperCamelCase_ : float) -> float: '''simple docstring''' return sum(c * (x**i) for i, c in enumerate(UpperCamelCase_)) def _A ( UpperCamelCase_ : S...
17
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_att...
233
"""simple docstring""" import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_uti...
233
1
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class _lowerCAmelCase ( lowercase ): """simple docstring""" __UpperCAmelCase : Tuple = (DDPMScheduler,) def _lowercase ( self : Optional...
17
"""simple docstring""" def _A ( UpperCamelCase_ : list[int]) -> float: '''simple docstring''' if not nums: # Makes sure that the list is not empty raise ValueError("List is empty") __lowercase = sum(UpperCamelCase_) / len(UpperCamelCase_) # Calculate the average...
17
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torc...
179
'''simple docstring''' 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, ) _snake_case : Dict ...
179
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def _A ( lowercase ): """simple docstring""" a =credit_card_...
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The ...
81
1
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 import lo...
208
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for...
208
1
from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBac...
95
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipe...
241
0
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi...
364
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
321
0
def snake_case_ ( lowerCAmelCase_ : int ): return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def snake_case_ ( lowerCAmelCase_ : int ): __lowercase : Tuple = 0 __lowercase : Optional[int] = number w...
233
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : List[str] = { '''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.jso...
233
1
from __future__ import annotations def UpperCamelCase ( __lowerCamelCase : list[int] ): snake_case : Optional[int] = len(__lowerCamelCase ) // 2 # choose the middle 3 elements snake_case : str = lst[m - 1 : m + 2] # if midd...
10
def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str ): if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("String lengths must match!" ) snake_case : Optional[Any] = 0 for chara, chara in zi...
10
1
"""simple docstring""" import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_av...
179
"""simple docstring""" import logging from transformers.configuration_utils import PretrainedConfig a_ = logging.getLogger(__name__) class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowerCamelCase = """masked_bert""" def __init__( self , ...
179
1
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArgument...
353
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __magic_name__ (__lowercase ): lowerCamelCase__ = ['''image_processor''', '''tokenizer'''] lowerCamelCase__ = '''ViTImageProcessor''' lowerCamel...
22
0
'''simple docstring''' import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_d...
208
'''simple docstring''' from collections.abc import Sequence def a_ ( _lowerCAmelCase ,_lowerCAmelCase ) -> float: return sum(c * (x**i) for i, c in enumerate(_lowerCAmelCase ) ) def a_ ( _lowerCAmelCase ,_lowerCAmelCas...
208
1
'''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, Auto...
217
'''simple docstring''' import heapq def _lowerCAmelCase ( lowerCamelCase_ : dict ): __lowercase = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue ...
217
1
import os import re import shutil import sys import tempfile import unittest import black snake_case : Any = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the...
94
'''simple docstring''' import math def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> float: if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of initia...
321
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Optional[int] = { """huggingface/time-series-transformer-t...
60
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer SCREAMING_SNAKE_CASE :List[str] = logging.getLogger(__name__) def lowerCAmelCase( )-> Union[str, Any]: """simple docstring""" ...
60
1
from __future__ import annotations def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" lowerCamelCase__: int =len(__a ) // 2 # choose the middle 3 elements lowerCamelCase__: int =lst[m - 1 : m + 2] # if middle element is peak if three[1] > ...
10
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: str =a while True: lowerCamelCase...
10
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils im...
201
def _A ( __magic_name__ ): lowercase__ = "" 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 _A ( __magic_name__ ): lowercase__ = [chr(i + 65 ) for i in range(26 )] # Remove duplicate...
201
1
"""simple docstring""" import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __snake_case : Union[str, Any] = [ os.path.join(os.path.dirname(__file__)...
269
'''simple docstring''' import os from datetime import datetime as dt from github import Github __SCREAMING_SNAKE_CASE :str = [ '''good first issue''', '''feature request''', '''wip''', ] def UpperCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' ...
22
0
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControl...
356
"""simple docstring""" import argparse import os import torch from transformers.utils import WEIGHTS_NAME __UpperCamelCase : int = ['''small''', '''medium''', '''large'''] __UpperCamelCase : str = '''lm_head.decoder.weight''' __UpperCamelCase : Dict = '''lm_hea...
309
0
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.proce...
217
"""simple docstring""" import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def a__ ( __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) ...
217
1
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils impor...
26
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remot...
26
1
"""simple docstring""" import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTes...
60
"""simple docstring""" def _snake_case ( _snake_case : list ): def merge(_snake_case : list , _snake_case : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) y...
60
1
class lowerCamelCase : """simple docstring""" def __init__( self : Tuple ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = {} def __A ( self : Tuple ) -> None: print(self.vertex ) for i in self.vertex: ...
305
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import...
305
1
import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, Pixa...
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
from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter im...
353
'''simple docstring''' import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def _snake_case ( A , A , A , A=5 ) -> List[str]: # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py ...
228
0
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class lowercase__ ( _a): UpperCamelCase_ = """MCTCTFeatureExtractor""" UpperCamelCase_ = """AutoTokenizer""" def __init__( self : Any , UpperCa...
182
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class a_ : def __init__( self ): _lowerCAmelCase : Any = """""" _lowerCAmelCase : List[Any] = """""" _lowerCAmelCase ...
309
0
"""simple docstring""" from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand _lowerCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid...
340
"""simple docstring""" import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( _a ): lowe...
340
1
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline _snake_case = datasets.utils.logging.get_logge...
26
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from...
26
1
"""simple docstring""" import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def _a ( _snake_case ): """simple docstring""" UpperCAmelCase = os.path.join(args.tf_model_dir , """parameters....
368
"""simple docstring""" import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { """post_ext...
234
0
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def UpperCamelCase ( __magic_name__ : Optional[Any] ) -> L...
305
def UpperCamelCase ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def UpperCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 ...
305
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) Uppe...
370
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_d...
313
0
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : str = { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/confi...
260
from __future__ import annotations def __A ( __lowerCamelCase , __lowerCamelCase = None ) -> list[list[str]]: a = word_bank or [] # create a table a = len(__lowerCamelCase ) + 1 a = [] for _ in range(__lowerCamelCa...
228
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> list: UpperCamelCase = word.split() def justify(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> str: UpperCamelCase = max_width - width ...
183
'''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/li...
183
1
from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand a_ = logging.get_logger(__name__) # pylint: disable=invalid-name def _a ( UpperCamelCase_ : str ...
340
from collections import defaultdict from math import gcd def _a ( UpperCamelCase_ : int = 1_500_000 ) -> int: """simple docstring""" lowerCAmelCase__ = defaultdict(UpperCamelCase_ ) lowerCAmelCase__ = 2 while 2 * euclid_m ...
340
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase__ : Optional[Any] = { '''configuration_data2vec_audio''': ['''DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecAudioConfig'''], '''co...
371
"""simple docstring""" import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_CO...
155
0
'''simple docstring''' from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class a__( UpperCAmelCase__ ): ...
297
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/conf...
234
0
import comet # From: unbabel-comet import torch import datasets _A = datasets.logging.get_logger(__name__) _A = '''\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel\'s Participation in the WMT20 Me...
360
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowercase_ ( __SCREAMING_SNAKE_CASE ): A__ : List[Any] = """EncodecFeatureExtractor""" A__ : Tuple = ("""T5Tokenizer""", """T5TokenizerFast"...
261
0
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effectiv...
223
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a__ : int = logging.get_logger(__name__) a__ : Optional[Any] = { '''SenseTime/deformable-detr''': '''https://huggingface.co/sensetime/deformable-detr/reso...
313
0
import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def UpperCAmelCase_ ( _A , _A , _A , _A=10_24 ): '''simple docstring''' SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ = [], [] SCREAMING_SNAK...
357
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
218
0
"""simple docstring""" import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _SCREAMING_SNAKE_CASE ...
183
"""simple docstring""" from __future__ import annotations def lowerCamelCase__ ( _lowerCamelCase : int ) -> list[int]: lowerCamelCase_ = [True] * limit lowerCamelCase_ = False lowerCamelCase_ = False ...
183
1
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowercase__ = TypeVar("T") class snake_case__ ( Generic[T] ): """simple docstring""" def __init__( self : Dict , UpperCamelCase...
353
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_mod...
83
0
"""simple docstring""" __lowercase = { "joule": 1.0, "kilojoule": 1000, "megajoule": 1000000, "gigajoule": 1000000000, "wattsecond": 1.0, "watthour": 3600, "kilowatthour": 3600000, "newtonmeter": 1.0, "calorie_nutr": 4186.8, "kilocalori...
40
"""simple docstring""" import argparse import json from tqdm import tqdm def lowercase () -> Dict: '''simple docstring''' lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--src_path""" , type=s...
155
0
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : int = {"vocab_file": "voc...
366
'''simple docstring''' def __lowerCamelCase ( A__ , A__ ) -> List[Any]: """simple docstring""" UpperCamelCase = '' for i in table: res += inp[i - 1] return res def __lowerCamelCase ( A__ ) -> Dict: ...
249
0
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a :List[str] = {"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]} try: if not is_torch_available(): ...
132
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data im...
261
0
"""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 ( AutoConfig, AutoModelFo...
359
"""simple docstring""" import torch def _snake_case ( ) -> Union[str, Any]: if torch.cuda.is_available(): lowerCamelCase_ : int =torch.cuda.device_count() else: lowerCamelCase_ : List[str] =0 print(F"""Successfully ...
209
0
'''simple docstring''' import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase : List[str] ...
2
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 _lowerCAmelCase : Optional[Any] = False class __magic_name__ ( unitt...
218
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase: List[str] = {"""configuration_vit_mae""": ["""VIT_MAE_PRETRAINED_CONFI...
336
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput ...
336
1
from itertools import permutations def lowerCamelCase_ ( UpperCamelCase__ : tuple ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if n...
90
'''simple docstring''' import unittest import numpy as np from transformers import DistilBertConfig, 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 j...
83
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging lo...
360
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _UpperCAmelCase = '▁' _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = ...
328
0
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake UpperCAmelCase_ : Tuple = numpy.array([0, 0]) UpperCAmelCase_ : Any = numpy.array([0.5, 0.8_6_6_0_2_5_4]) UpperCAmelCase_ : Tuple ...
32
"""simple docstring""" import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_imag...
249
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json""", # See all WavLM mod...
369
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _A = { """configuration_layoutlmv3""": [ """LAYOUTLMV3_P...
166
0
import pickle import numpy as np from matplotlib import pyplot as plt class a__ : def __init__( self , _A , _A , _A , _A , _A , _A=0.2 , _A=0.2 ): """simple docstring""" __lowerCAmelCase = bp_numa __lowerCAmelCase ...
92
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, W...
209
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
199
'''simple docstring''' from timeit import timeit def _A ( snake_case ) -> int: if number < 0: raise ValueError("the value of input must not be negative" ) _lowercase : Union[str, Any] = 0 while number: number &= number - 1 result += 1 ...
199
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCamelCase : List[str] = {"configuration_vit_mae": ["VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMAEConfig"]} tr...
336
from __future__ import annotations def a__ ( UpperCAmelCase : int , UpperCAmelCase : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number...
336
1
"""simple docstring""" import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowercase__ ( l...
310
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowerCamelCase__ = "\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...
310
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""",...
68
from __future__ import annotations from collections.abc import Callable def A_ ( snake_case : Callable[[int | float], int | float] , snake_case : int | float , snake_case : int | float , snake_case : int = 100 , ) ...
328
0
import inspect import unittest from transformers import MobileViTConfig 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_configuration_common import ConfigTester from ......
367
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
75
0
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common impor...
273
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { """alibaba-damo/mgp-str-base""": """https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json""", }...
166
0
import os import pytest from attr import dataclass _UpperCAmelCase = 'us-east-1' # defaults region @dataclass class _UpperCamelCase : _UpperCamelCase : str _UpperCamelCase : Any = '''arn:aws:iam::558105141721:role/sagemaker_execution_role''' _Upper...
328
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _UpperCamelCase : def __init__( self: str ) -> Any: """simple docstring""" UpperCamelCase_ = "" UpperCamelCase_ = "...
328
1
def a_ ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' return abs(SCREAMING_SNAKE_CASE__ ) if a == 0 else greatest_common_divisor(b % a , SCREAMING_SNAKE_CASE__ ) def a_ ( SCREAMING_SNAKE_CASE__ :...
199
import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common imp...
199
1
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokeniz...
33
from typing import List from .keymap import KEYMAP, get_character def __lowerCAmelCase ( a__ ) -> List[str]: def decorator(a__ ): __a = getattr(a__ , '''handle_key''' , [] ) handle += [key] setattr(a__ , '''handle_key''' , a__ ...
33
1
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __snake_case = {'''UserAgent''': UserAgent().random} def _A ( _lowercase ) -> dict: """simple docstring""" ...
310
import torch from transformers import AutoModel class __lowerCamelCase (torch.nn.Module ): def __init__( self: Union[str, Any],A_: Tuple="sayef/fsner-bert-base-uncased" ): '''simple docstring''' super(A_,self...
310
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class lowerCAmelCase_ : '''simple docstring''' __lowercase : int __lowercase : TreeNode | None = None __lowercase ...
370
'''simple docstring''' import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers....
184
0
"""simple docstring""" __a = """2.13.1""" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match thi...
66
'''simple docstring''' import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : Optional[int] ...
75
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Any = logging.get_logger(__name__) A_ : int = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/res...
141
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable A_ : List[Any] = {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']} try: if not is_tokenizers_avail...
141
1
from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase__ : List[Any] = logging.get_logger(__name__) lowercase__ : List[Any] = { "speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config...
328
def A_ ( snake_case : list ) -> list: '''simple docstring''' __UpperCamelCase = len(snake_case ) for i in range(1 , snake_case ): __UpperCamelCase = collection[i] __UpperCamelCase = 0 ...
328
1
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class A__ : '''simple docstring''' def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any]) -> str: """simple do...
58
"""simple docstring""" __snake_case : Any = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66...
58
1
"""simple docstring""" import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() __A : Tuple = logging.get_logger(__name__) __A : Dict = { ...
33
"""simple docstring""" from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def lowercase ( __snake_case : str , __snake_case : str , __snake_case : Optional[str] = None ): if version.par...
33
1
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class _SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE = 16 , _SCREAMING_SNAKE_CASE = 88 , _SCREAMING_SNAKE_CASE = None ...
49
__A : List[Any] = [ 9_99, 8_00, 7_99, 6_00, 5_99, 5_00, 4_00, 3_99, 3_77, 3_55, 3_33, 3_11, 2_88, 2_66, 2_44, 2_22, 2_00, 1_99, 1_77, 1_55, 1_33, 1_11, 88, 66, 44, 22, 0, ] __A : int = [ ...
49
1
'''simple docstring''' import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": lowerCAmelCase__ = '''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(input('''S...
104
def lowercase_ ( _A : int , _A : int ): """simple docstring""" while a != 0: lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = b % a, a return b def lowercase_ ( _A : int , _A : int ): ...
184
0
"""simple docstring""" __UpperCamelCase = [ '''Audio''', '''Array2D''', '''Array3D''', '''Array4D''', '''Array5D''', '''ClassLabel''', '''Features''', '''Sequence''', '''Value''', '''Image''', '''Translation''', '''TranslationVariableLanguages''', ] from .a...
312
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .token...
312
1
'''simple docstring''' import heapq def __UpperCamelCase ( lowercase__ : dict ): '''simple docstring''' __lowercase =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Prio...
141
'''simple docstring''' UpperCAmelCase = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' UpperCAmelCas...
141
1
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __A = HUGGINGFACE_HUB_CACHE __A = 'config.json' __A = 'diffusion_pytorch_model.bin' __A = 'diffusion_flax_model.msgpack' __A = 'model.onnx' __A = 'diffusion_pytorch_mode...
370
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": __A = input('Enter image url: ').strip() print(f'Downloading image from {url} ...') __A = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the co...
75
0
'''simple docstring''' from sklearn.metrics import matthews_corrcoef import datasets lowercase_ = """ Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into acc...
58
'''simple docstring''' from collections.abc import Sequence def lowerCamelCase ( __lowerCamelCase : Sequence[float] , __lowerCamelCase : bool = False ) ->float: if not arr: return 0 _SCREAMING_SNAKE_CASE = 0 if allow_empty_subarrays else float("""-...
58
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A__ : Any = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP'''...
365
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers...
0
0
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 ( AlbertTokenizer, AutoTokenize...
49
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..mode...
49
1
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelera...
366
"""simple docstring""" from __future__ import annotations from collections.abc import MutableSequence class UpperCamelCase_ : def __init__( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : MutableSequence[float] ) -> None: if len(low...
253
0
import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def __snake_case ( __UpperCamelCase : Tuple ): """simple docstring""" A_ = ...
312
__a :Dict = '0.18.2' from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_availa...
312
1
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def snake_case_ (__A : Any ) -> str: __lowerCAmelCase : Tuple = args.pruning_method __lowerCAmelCase : Li...
139
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(): ...
139
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : Optional[Any] = { """huggingface/time-series-transformer-tourism-monthly""": ( """https://huggingface.co/huggingfa...
207
'''simple docstring''' def a_ ( __snake_case : Any , __snake_case : List[str] ) -> str: """simple docstring""" lowerCamelCase_ ='''''' for i in table: res += inp[i - 1] return res def a_ ( ...
75
0
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met cla...
52
'''simple docstring''' # Function to print upper half of diamond (pyramid) def _A ( A__ ): """simple docstring""" for i in range(0 , A__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1...
52
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def lowerCAmelCase_ ( __lowerCAmelCase )-> Optional[Any]: ...
348
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils im...
0
0
def lowerCamelCase_ ( UpperCamelCase__ : List[Any] = 200_0000 ): '''simple docstring''' UpperCamelCase__ = [0 for i in range(n + 1 )] UpperCamelCase__ = 1 UpperCamelCase__ = 1 for i in range(2, int(n**0.5 ) + 1 ...
366
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class __lowercase ( unittest.TestCase ): ...
35
0
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_mo...
195
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase : List[str] = logging.get_logger(__name__) class _A ( __magic_name__ , __magic_nam...
253
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 ...
304
import math from datetime import datetime, timedelta def _lowerCamelCase( lowercase__ ) -> datetime: '''simple docstring''' __lowercase= year % 1_9 __lowercase= year % 4 __lowercase= year % 7 __lowercase= math.floor(year / 1_0_0 ) __lowercase= ...
304
1
'''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, get_resize_output_image_size, normalize, rescale, resize, ...
139
'''simple docstring''' from __future__ import annotations def A_ ( snake_case , snake_case , snake_case , ): if (stress, tangential_force, area).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif stress < 0...
139
1
import math def a_ ( lowerCAmelCase_ : float, lowerCAmelCase_ : float ): if initial_intensity < 0: raise ValueError('The value of intensity cannot be negative' ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueE...
364
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 import ...
207
0
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncode...
52
from __future__ import annotations from functools import lru_cache from math import ceil __lowerCamelCase : str = 100 __lowerCamelCase : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) __lowerCamelCase : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if pri...
52
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_...
116
import os import sys import unittest lowerCAmelCase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, fin...
116
1
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable lowerCAmelCase__ = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJap...
104
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __a = { "configuration_bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig", "BloomOnnxConfig"], } try: if not i...
35
0
'''simple docstring''' from math import factorial class UpperCamelCase__ : """simple docstring""" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Tuple = real ...
358
'''simple docstring''' lowerCAmelCase : List[str] = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface...
25
0
'''simple docstring''' from __future__ import annotations import numpy as np def __UpperCAmelCase ( A : list[float] ) -> Tuple: return np.maximum(0 , A ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
304
'''simple docstring''' import random class snake_case__ : @staticmethod def A ( _A : str ) -> tuple[list[int], list[int]]: UpperCAmelCase_ : Dict = [ord(_A ) for i in text] UpperCAmelCase_ : List[str] = [] UpperCAmelCase_ : ...
304
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config im...
353
"""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.apach...
188
0
'''simple docstring''' def a ( __a , __a ) -> str: '''simple docstring''' if not isinstance(__a , __a ): raise ValueError('''iterations must be defined as integers''' ) if not isinstance(__a , __a ) or not number >= 1: raise ValueError( ...
97
import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _UpperCAm...
207
0
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 logging lowercase : int = logging.get_logger(__name__) lowercase : ...
171
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Dict = logging.get_logger(__name__) lowercase : Union[str, Any] = { "google/canine-s": "https://huggingface.co/google/canine-s/resolve/main/config.json", # See all CANINE models at...
171
1
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: """simple docstring""" if len(_lowerCAmelCase ) != len(_lowerCAmelCase ): raise ValueError("""The length of profit and weight must be same.""" ) if max_weight <= 0: ...
116
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE__ ( metaclass=SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __lowerCamelCase : List[str] = ["torch", "transformers", "onnx"] def __init__( self, *lowerCamelCase__, **lowerCam...
116
1
"""simple docstring""" 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.se...
318
"""simple docstring""" import argparse from collections import defaultdict import yaml UpperCAmelCase_ : Optional[Any] = """docs/source/en/_toctree.yml""" def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str ...
318
1
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
"""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 lowerCAmelCase_ (unittest.TestCase ): """simple docstring""" ...
25
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_dev...
350
"""simple docstring""" def A ( snake_case :int ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") UpperCamelCase : Union[str...
263
0