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
def a ( snake_case__: int = 100 ): '''simple docstring''' lowercase_ = (n * (n + 1) // 2) ** 2 lowercase_ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
30
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelO...
30
1
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_availab...
354
from bisect import bisect from itertools import accumulate def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: lowercase : Dict = sorted(zip(SCREAMING_SNAKE_CASE__ , SCREAMIN...
285
0
'''simple docstring''' from __future__ import annotations from cmath import sqrt def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' if a == 0: raise ValueError('''Coefficient \'a\' must not be zero....
3
'''simple docstring''' import os import sys import unittest lowercase : Dict = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E40...
3
1
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, to_channel_dimension_format, ) from ...
358
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWit...
130
0
import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger _lowercase: Any = "<<<<<<< This should probably be modified because it mentions: " _lowercase: List[Any] = "======...
227
def a( A : list ) -> list: """simple docstring""" if any(not isinstance(A , A ) or x < 0 for x in sequence ): raise TypeError("Sequence must be list of non-negative integers" ) for _ in range(len(A ) ): for i, (...
227
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_t...
173
def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->list[int]: """simple docstring""" lowercase : Dict = int(_UpperCamelCase ) # Initialize Result lowercase : Union[str, Any] = [] # Traverse through all denomi...
173
1
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(...
127
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached...
127
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) _lowerCAmelCase : List[str] = { '''camembert-base...
366
"""simple docstring""" import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax imp...
340
0
'''simple docstring''' from __future__ import annotations import requests def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(s...
85
def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' if edge <= 0 or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError('Length must be a positive.' ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge...
285
0
'''simple docstring''' import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel __A : List[str] = HfApi() __A : Optional[Any] = {} # fmt: off __A : Tuple = torch.tensor([ -0.7_5_1_5, -1.6_8_8_3, ...
356
'''simple docstring''' from ..utils import DummyObject, requires_backends class __snake_case ( metaclass=_SCREAMING_SNAKE_CASE): """simple docstring""" lowercase = ['note_seq'] def __init__( self : Tuple , *lowerC...
89
0
"""simple docstring""" 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 __magic_name__ = logging.get_logger(__name...
100
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case__(_UpperCamelCase , _UpperCamelCase ): """simple docstring""" @register_to_config ...
130
0
from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_c...
353
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers ...
89
0
import os from collections.abc import Iterator def lowercase_( SCREAMING_SNAKE_CASE_ = "." ): '''simple docstring''' for dir_path, dir_names, filenames in os.walk(UpperCAmelCase_ ): lowerCamelCase : Union[str, Any] = [d for d in dir_names if d != 'scripts' and d[0] not ...
283
"""simple docstring""" import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCL...
172
0
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a : str = lo...
363
'''simple docstring''' import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor a : Dict = logging.get_logger(__name__) class UpperCamelCase_ ( __magic_name__ ): def __init__( self , *A , **A ) -> ...
338
0
"""simple docstring""" import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational im...
115
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline a_ = { '''n_samples''': 64, '''horizon''': 32, '''num_inference_steps''': 20, '''n_guide_steps''': 2, # can set to 0 for faster sampling, does not use value network '''scale_grad_by_...
340
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokenizer else: low...
282
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class A ( nn.M...
282
1
import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # no...
18
'''simple docstring''' __lowerCAmelCase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def __lower...
89
0
"""simple docstring""" import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_ut...
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 argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel lowerCAmelCase__ : Optional[Any] = False lowerCAmelCase__ : Any = True lowerCAmelCase__ : Any = False if __name__ == "__...
143
'''simple docstring''' import math def __lowerCamelCase ( lowerCAmelCase_ ) -> bool: _a : Optional[int] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCa...
89
0
"""simple docstring""" import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when ...
353
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def _snake_case ( _snake_case : List[str] ): lowerCAmelCase : Union[str, Any] = SwinConfig(image_size...
314
0
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMix...
34
lowercase__ : Optional[int] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def SCREAMING_SNAKE_CASE_ ( ) -> None: lowerCAmelCase = input('''Enter message: ''' ) lowerCAmelCase = input('''Enter key [alphanumeric]: ''' ) lowerCAmelCase = input('''Encrypt/Decrypt [...
338
0
def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = len(snake_case_ ) _A : str = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element ...
356
import inspect import unittest from transformers import ViTMSNConfig 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 ...test_...
343
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import Blend...
282
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
1
"""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 .tokeni...
364
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase = {'''configuration_mmbt''': ['''MMBTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except O...
312
0
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop...
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 typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE = {"tokenization_byt5": ["ByT5Tokenizer"]} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys SCREAMING_SNAKE_CASE = _LazyModule(__name__, glob...
230
"""simple docstring""" import baseaa def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> bytes: return baseaa.aaaencode(string.encode("utf-8" ) ) def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: return baseaa.aaadecode(lowercase_ ).decode(...
230
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a_ = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer''']...
340
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.pat...
314
0
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets lowercase__ = '''\ @inproceedings{snover-etal-2006-study, title = "A Study of Translation Edit Rate with Targeted Human Annotation", author = "Snover, Matt...
369
'''simple docstring''' from math import pi, sqrt, tan def _lowerCAmelCase ( __snake_case : float ) -> float: if side_length < 0: raise ValueError('surface_area_cube() only accepts non-negative values' ) return 6 * side_length**2 ...
190
0
"""simple docstring""" 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, Trainin...
172
from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from t...
343
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, ...
356
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 ..auto import CONFIG_MAPPING lowercase__ : Optional[Any] = logging.get_logger(__name__) l...
180
0
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging _a = log...
322
import functools from typing import Any def __snake_case ( __UpperCamelCase : str ,__UpperCamelCase : list[str] ): """simple docstring""" if not isinstance(__UpperCamelCase ,__UpperCamelCase ) or len(__UpperCamelCase ) == 0: raise ValueE...
312
0
"""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...
161
"""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-...
161
1
import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version f...
230
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets A__ = datasets.logging.get_logger(__name__) A__ = '''\ @InProceedings{moosavi2019minimum, author = { Naf...
230
1
'''simple docstring''' import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenizatio...
352
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : Optional[int] = { "configuration_canine": ["CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP", "CanineConf...
92
0
import numpy as np class __A : """simple docstring""" def __init__( self , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None ): """...
71
'''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 toke...
190
0
import argparse from collections import defaultdict import yaml __lowerCAmelCase = '''docs/source/en/_toctree.yml''' def snake_case_ ( snake_case ) -> Dict: lowercase__: List[str] = defaultdict(snake_case ) lowercase__: Dic...
288
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets __lowerCAmelCase = '''\ @inproceedings{popovic-2015-chrf, title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation", author = "Popovi{\'c}, Maja", booktitle = "Proceeding...
288
1
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAM...
46
import collections import importlib.util import os import re from pathlib import Path _SCREAMING_SNAKE_CASE = 'src/transformers' # Matches is_xxx_available() _SCREAMING_SNAKE_CASE = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} _SCREAMI...
180
0
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase ( lowerCamelCase_ :Dict , ...
8
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def UpperCAmelCase ( lowerCamelCase_ :Callable[[int | float], int | float] , lowerCamelCase_ :int | float , lowerCamelCase_ :int | float , lowerCamelCase_ :int = 1_00 , ): ...
8
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licens...
161
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffuse...
161
1
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTeste...
78
import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> float: '''simple docstring''' UpperCAmelCase : Any =x UpperCAmelCase : List[str] =y for ...
78
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 1000 ) -> int: _lowerCAmelCase , _lowerCAmelCase : Tuple = 1, 1 _lowerCAmelCase : Optional[Any] = 2 while True: _lowerCAmelCase : Any = 0 ...
44
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def...
92
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = { '''configuration_lxmert''': ['''LXMERT_PRETRAINED_CONFIG_ARCHI...
357
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 1000 ) -> int: """simple docstring""" return sum(e for e in range(3 , __magic_name__ ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(F'''{solution() = }''')
62
0
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism...
288
"""simple docstring""" def _UpperCAmelCase ( __lowerCamelCase : int = 1_00_00_00 ) -> int: _snake_case = limit + 1 _snake_case = [0] * limit for first_term in range(1 , __lowerCamelCase ): for n in range(__lowerCamelCase , __lowerC...
288
1
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: if len(_SCREAMING_SNAKE_CASE ) <= 1: return [tuple(_SCREAMING_SNAKE_CASE )] snake_case_ = [] def generate(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if k == 1:...
233
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed fro...
233
1
import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CAS...
8
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class snake_case_ ( __A ): '''simple docstring''' def __init_...
8
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowercase_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDepende...
11
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmel...
11
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available snake_case_ = { """configuration_ernie""": ["""ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ErnieConfig""", """...
78
"""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 snake_case_ = logging.get_logger(__name__) snake...
78
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline 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 ..pipe...
147
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_...
147
1
def lowerCamelCase__ ( ): '''simple docstring''' __lowerCamelCase = [] __lowerCamelCase = 1 while len(SCREAMING_SNAKE_CASE__ ) < 1E6: constant.append(str(SCREAMING_SNAKE_CASE__ ) ) i += 1 __lowerCamelCase = ...
12
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDepend...
62
0
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins __UpperCAmelCase :Tuple = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"] def _a ( _lowercase : Tuple , _lowercase : int ): ...
240
'''simple docstring''' def _a ( _lowercase : List[str] ): '''simple docstring''' __UpperCAmelCase : str = 1 __UpperCAmelCase : List[str] = 2 while i * i <= n: __UpperCAmelCase : Optional[...
240
1
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() lowerCamelCase : Union[str,...
233
# flake8: noqa # Lint as: python3 lowerCamelCase : Optional[Any] = [ '''VerificationMode''', '''Version''', '''disable_progress_bar''', '''enable_progress_bar''', '''is_progress_bar_enabled''', '''experimental''', ] from .info_utils import VerificationMode from .log...
233
1
from __future__ import annotations from random import choice def A__ ( SCREAMING_SNAKE_CASE__) -> Optional[Any]: return choice(UpperCAmelCase_) def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> int: __snake_case: Optional[int] = ...
357
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( "The `image_to_image.py` script is outdated. Please use directly `from diffusers import" " StableDiffusionImg2ImgPipeline` instead." )
293
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCAmelCase__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCA...
11
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import Back...
11
1
'''simple docstring''' from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time lowerCAmelCase__ = Lock() def _A ( A__ , A__ , A__ , A__ , A__ , A__ , A__ ): """simple d...
355
'''simple docstring''' lowerCAmelCase__ = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def _A ( ): """simple docstring""" __lowercase = input('''Enter message: ''' ) __lowercase = input('''Enter key [alphanumeric]: ''' ) __lowercase = input('''Encrypt/Dec...
52
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a : Optional[int] = {'configuration_wavlm': ['WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WavLMConfig']} try: if not is_torch_available(): raise OptionalDependencyNot...
147
import os # Precomputes a list of the 100 first triangular numbers a : Optional[Any] = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowerCAmelCase_ (): """simple docstring""" UpperCAmelCase_: Any = os.path.dirname(os.path.real...
147
1
from math import pi, sqrt def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Union[str, Any]: if num <= 0: raise ValueError("math domain error" ) if num > 171.5: raise OverflowError("math range error" ) elif num - int(__SCRE...
370
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> list[int]: UpperCamelCase__ : Optional[Any] = 0 UpperCamelCase__ : Any = len(__lowerCAmelCase ) - 1 while i < ...
196
0
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( ...
240
def __lowercase ( __lowerCAmelCase : int , __lowerCAmelCase : float , __lowerCAmelCase : float ): return round(float(moles / volume ) * nfactor ) def __lowercase ( __lowerCAmelCase : float , __lowerCAmelCase : floa...
240
1
'''simple docstring''' from __future__ import annotations import bisect def UpperCAmelCase_ ( __lowercase : list[int] , __lowercase : int , __lowercase : int = 0 , __lowercase : int = -1 ) -> int: '''simple docstring''' ...
156
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE :Dict = { '''configuration_upernet''': ['''UperNetConfig'''], } try: if not is_torch_available(): raise OptionalDepende...
156
1
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __lowerCAmelCase : Tuple = '\\n@misc{chen2021evaluating,\n title={Ev...
88
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise Type...
293
0
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap _A = 'Usage of script: script_name <size_of_canvas:int>' _A = [0] * 100 + [1] * 10 random.shuffle(choice) def lowerCamelCase__ ( a__ : Optional[Any] )...
364
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { '''kakaobrain/align-base''': '''https://huggingface.co/kakaobrain/align-ba...
261
0
'''simple docstring''' from __future__ import annotations import typing from collections import Counter def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : typing.Counter[int] = Counter() for base in range(1 , max_p...
3
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder impo...
52
0
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase = 100 ) -> int: '''simple docstring''' lowerCAmelCase : Any = 0 lowerCAmelCase : int = 0 for i in range(1, n + 1 ): sum_of_squares += i**2 sum_of_ints +=...
352
from math import pi, sqrt, tan def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> float: '''simple docstring''' if side_length < 0: raise ValueError('surface_area_cube() only accepts non-negative values' ) return 6 * side_length**2 def SCREAMING_SNAKE_CASE__ ( ...
323
0
"""simple docstring""" from math import loga def __UpperCAmelCase ( __lowerCamelCase ) -> int: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): raise TypeError('...
16
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from...
196
0
'''simple docstring''' import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel lowercase__ : Optional[int] = HfApi() lowercase__ : Dict = {} # fmt: off lowercase__ : List[str] = torch.tensor([ -0.7515, ...
190
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( __snake_case : list[int | str] ) -> None: create_state_space_tree(__snake_case , [] , 0 , [0 for i in range(len(__snake_case ) )] ) ...
190
1
class __lowerCAmelCase : """simple docstring""" def __init__( self : str , _snake_case : int , _snake_case : str , _snake_case : Optional[int] ): __lowercase : Tuple = None __lowercase : Dict =...
156
import numpy as np from PIL import Image def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> np.ndarray: __lowercase : Optional[int] = np.array(__lowerCAmelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('''The input ...
156
1
'''simple docstring''' import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class lowercase_ ( A ): """simple docstring""" lowerCamelCase_ = (IPNDMScheduler,) lowerCamelCase_ = (('''num_inference_...
111
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( __A : int ) -> int: if n == 1 or not isinstance(__A , __A ): return 0 elif n == 2: return 1 else: _SCREAMING_SNAKE_CASE = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i -...
111
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ : int = logging.get_logger(__name__) snake_case_ : str = { "bert-base-uncased": "h...
51
"""simple docstring""" 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_com...
261
0
'''simple docstring''' import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowerCAmel...
351
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE_: int ={ 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'configuratio...
106
0
"""simple docstring""" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Any , ...
46
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class UpperCamelCase__ ( lowercase_ ): ...
323
0
'''simple docstring''' def _a( UpperCamelCase__ : str, UpperCamelCase__ : int ): '''simple docstring''' return [sentence[i : i + ngram_size] for i in range(len(UpperCamelCase__ ) - ngram_size + 1 )] if __name__ == "__main__": from do...
359
'''simple docstring''' from datetime import datetime as dt import os from github import Github a_ = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def _a( ): '''simple d...
222
0
'''simple docstring''' import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTester...
190
'''simple docstring''' from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def _lowerCAmelCase ( __snake_case : Optional[Any] , __snake_case : Optional[i...
190
1
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator,...
364
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowercase_ = { "text_branch": "text_model", "audio_branch": "audio_model.audio_encoder", "attn": "attention.self", "self.proj": "output.dense", "att...
20
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase : Optional[int] = logging.get_logger(__name__) __UpperCAmelCase : Optional[int] ...
111
from statistics import mean import numpy as np def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> list: __snake_case: List[Any] = 0 # Number of processes finished __snake_case: Unio...
111
1
"""simple docstring""" import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def __UpperCamelCase ( _A ): def wrapper(*_A , **_A ): lowerCAmelCase_ = timeit.default_timer() ...
353
import string def __UpperCamelCase ( _A ): for key in range(len(string.ascii_uppercase ) ): lowerCAmelCase_ = '''''' for symbol in message: if symbol in string.ascii_uppercase: lowerCAmelCase_ = string.ascii_up...
167
0
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, ...
20
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __UpperCamelCase : Tuple = TypeVar('''T''') class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" lowerc...
106
0
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_xlnet ...
369
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, Compu...
335
0
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( lowercase : Optional[int] , lowercase : Any , lowercase : Dict , lowercase : List[str] ): '''simple docstring''' lowerCamelCase_ = [] lowerCamelCas...
204
from random import randint from tempfile import TemporaryFile import numpy as np def A ( lowercase , lowercase , lowercase ) -> str: '''simple docstring''' UpperCamelCase = 0 if start < end: UpperCamelCase = randint(lowercase , lowercase ) Upper...
222
0
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torc...
357
from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge __snake_case = [ '''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the''' '''...
78
0
from sklearn.metrics import recall_score import datasets lowerCAmelCase : Optional[int] = """ Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is t...
13
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, ...
20
0
import logging from transformers import PretrainedConfig lowerCAmelCase = logging.getLogger(__name__) lowerCAmelCase = { 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class _a ...
93
from collections.abc import Sequence from queue import Queue class _a : def __init__( self: Tuple , UpperCamelCase_: Optional[int] , UpperCamelCase_: int , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Union[str, Any]=None , U...
93
1
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 from .pt_to_tf import PTtoTFCommand...
65
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
167
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __A : List[str] = 'src/dif...
49
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 __A : Any = '▁' __A : Union[s...
49
1
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 200 ) -> int: _a = [1, 2, 5, 10, 20, 50, 100, 200] _a = [0] * (pence + 1) _a = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(lowercase , pence +...
63
"""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...
335
0
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 if is_torch_available(): import torch if...
208
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase : str = {name: get...
208
1
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy UpperCAmelCase__ = logging.get_logger(__name__) class ...
5
"""simple docstring""" from __future__ import annotations def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): UpperCAmelCase = list(range(len(lowercase_ ) ) ) UpperCAmelCase = [v / w for v, w in zip(lowercase_ , lowercase_ ...
78
0
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo _lowerCAmelCase : Optional[int] = '''\ @misc{wu2016googles, title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Mach...
340
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging _lowerCAmelCase : Dict ...
340
1
'''simple docstring''' import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ...
93
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = ...
93
1
"""simple docstring""" def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> str: snake_case_ = len(UpperCAmelCase ) snake_case_ = len(UpperCAmelCase ) snake_case_ = ( first_str_length if first_str_length > second_str_length else second_str_length ) snake_case_ ...
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
import functools def __snake_case ( _UpperCAmelCase , _UpperCAmelCase ): __a = len(_UpperCAmelCase ) __a = len(_UpperCAmelCase ) @functools.cache def min_distance(_UpperCAmelCase , _UpperCAmelCase ) -> int: # if first word index is o...
49
import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Initialise PyTorch model ...
49
1
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 jax.numpy as jnp ...
325
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCamelCase__ =logging.getLogger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstri...
325
1
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTest...
208
'''simple docstring''' import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.tra...
208
1
from itertools import product def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: int , lowerCAmelCase: int ) -> list[int]: _UpperCAmelCase : Union[str, Any] = sides_number _UpperCAmelCase : Dict = max_face_number * dice_number _UpperCAmelCa...
189
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: int ) -> int: if not isinstance(lowerCAmelCase , lowerCAmelCase ): raise TypeError("Input value must be an 'int' type" ) _UpperCAmelCase : List[Any] = 0 while number: position += 1 number ...
189
1
"""simple docstring""" import os import pytest from transformers.dynamic_module_utils import get_imports A_ : Optional[int] = "\nimport os\n" A_ : Tuple = "\ndef foo():\n import os\n return False\n" A_ : Any = "\ndef foo():\n def ...
165
'''simple docstring''' def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if discount_rate < 0: raise ValueError("""Discount rate cannot be negative""" ) if not cash_flows: raise ValueError("""Cash flows list cannot be ...
341
0
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_...
371
'''simple docstring''' lowerCAmelCase : List[Any] = {str(digit): digit**5 for digit in range(10)} def A_( A : int): return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A)) def A_( ): return sum( number for n...
251
0
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 transformer...
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 from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() lowercase__ : Union[str, Any] = logging.get_logger(__name__) def _lowerCAmelCase ( __snake_case...
366
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, T...
190
0
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 jax.numpy as jnp ...
325
from math import isqrt, loga def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> list[int]: __lowercase = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , ...
325
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { 'xlm-robert...
187
'''simple docstring''' import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( ...
187
1
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 ...
189
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __a ( unit...
189
1
import os from typing import Dict, List, Tuple, TypeVar, Union __snake_case : Union[str, Any] =TypeVar('T') __snake_case : Tuple =Union[List[T], Tuple[T, ...]] __snake_case : Union[str, Any] =Union[T, List[T], Dict[str, T]] __snake_case : Tuple =Union[str, bytes, os.PathLike]
94
__snake_case : Any ='\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' __snake_case : Tuple =[{'type':...
94
1