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 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_video_inputs if is_torc...
238
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def snake_case__ ( __lowerCamelCase : List[Any] , __lowerCam...
238
1
def _UpperCamelCase ( snake_case__ ) -> bool: if not isinstance(__lowerCAmelCase, __lowerCAmelCase ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(__lowerCAmelCase ) == 0: raise ValueError("In...
350
import math _snake_case = 10 _snake_case = 7 _snake_case = BALLS_PER_COLOUR * NUM_COLOURS def _UpperCamelCase ( snake_case__ = 20 ) -> str: __UpperCAmelCase : Optional[Any] = math.comb(snake_case__, snake_case__ ) ...
342
0
import os from math import logaa def __magic_name__ ( __lowerCAmelCase : str = "base_exp.txt" ) -> int: __lowerCamelCase = 0 __lowerCamelCase = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(__lowerCAmelCase ) , __lowerCAmelCase ) ) ...
270
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_p...
270
1
'''simple docstring''' def _A ( snake_case ) -> int: # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection _lowercase : Dict = len(__a ) _lowercase : Optional[int] = ...
350
'''simple docstring''' import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case ...
199
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_c...
298
'''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 _lowerCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for...
298
1
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( A__ ): def __init__( self , *__A , **__A ) -> None: w...
356
"""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 im...
1
0
from __future__ import annotations from scipy.special import comb # type: ignore class UpperCAmelCase_ : def __init__( self, __a): '''simple docstring''' _lowerCAmelCase : Optional[int] = list_of_points # Degree determines the f...
36
import colorsys from PIL import Image # type: ignore def __UpperCamelCase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : int ): __a : Any = x __a : List[Any] = y for step in range(lowerCAmelCase__ ): # noqa: B007 __a : ...
216
0
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_gpu, require_vision, slow, torc...
51
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 BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling...
51
1
"""simple docstring""" import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class SCREAMI...
106
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __UpperCamelCase : Dict = { '''...
106
1
'''simple docstring''' def _lowerCAmelCase ( lowercase = 1 , lowercase = 1000 ) -> int: __lowerCAmelCase = 1 __lowerCAmelCase = 0 for divide_by_number in range(lowercase , digit + 1 ): __lowerCAmelCase = [] __lowerCAmelCase ...
363
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tenso...
46
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a_ = ...
76
"""simple docstring""" import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor _lowercase : Any = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' def __init__...
238
0
import torch from transformers import AutoModel class _snake_case ( torch.nn.Module ): def __init__( self , a="sayef/fsner-bert-base-uncased") -> Optional[Any]: super(__snake_case , self).__init__() SCREAMING_SNAKE_CASE = AutoModel.from_pretrained...
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json...
327
0
import logging import os from .state import PartialState class a__ ( logging.LoggerAdapter ): @staticmethod def __SCREAMING_SNAKE_CASE( _A ): """simple docstring""" __lowerCAmelCase = PartialState() return not main_proces...
92
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @da...
92
1
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class A_ ( unittest.TestCase ): '''simple docstring''' def ...
194
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = len(SCREAMING_SNAKE_CASE__ ) for i in range(n - 1 ): for j in range(i + 1 , SCREAMING_SNAKE_CASE__ ): if arr[i] > arr[j]: num_inversions +=...
194
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : Optional[int] = logging.get_logger(__name__) lowercase__ : str = { 'transfo-xl-wt103': 'https://huggingface.co/transfo-xl-wt103/resolve/main/config.json', }...
324
"""simple docstring""" A__ : Optional[int] = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', ...
144
0
"""simple docstring""" import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __lowerCAmelCase : Optional[Any] =4 __lowerCAmelCase : int =...
32
"""simple docstring""" 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(): fr...
32
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, St...
130
lowerCAmelCase__ = 0 # The first color of the flag. lowerCAmelCase__ = 1 # The second color of the flag. lowerCAmelCase__ = 2 # The third color of the flag. lowerCAmelCase__ = (red, white, blue) def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" ...
130
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILIma...
363
"""simple docstring""" def __lowercase ( ) ->Tuple: '''simple docstring''' __A : str = [] __A : List[Any] = 1 while len(snake_case_ ) < 1e6: constant.append(str(snake_case_ ) ) i += 1 __A : ...
291
0
UpperCAmelCase : Tuple = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} UpperCAmelCase : Optional[int] = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _A ( SCREAMING_SNAKE_CASE : dict[int, list[int]] , SCREAMING_SNAKE_CASE : int ...
95
'''simple docstring''' import math def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase_ = input("Enter message: " ) UpperCAmelCase_ = int(input(f"""Enter key [2-{len(snake_case_ ) - 1}]: """ ) ) UpperCAmelCase_ ...
1
0
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): return round(float(moles / volume) * nfactor) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): return round(float((moles * 0.08_21 * temperature) / (vol...
327
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption t...
327
1
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, ...
74
'''simple docstring''' import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def __a(SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : str ...
158
0
def _lowerCAmelCase ( A__: int = 1000 ): '''simple docstring''' UpperCAmelCase = 2**power UpperCAmelCase = 0 while n: UpperCAmelCase , UpperCAmelCase = r + n % 10, n // 10 return r if __name__ == "__main__": ...
152
def _lowerCAmelCase ( A__: list[int] , A__: list[int] ): '''simple docstring''' UpperCAmelCase = len(A__ ) print('''The following activities are selected:''' ) # The first activity is always selected UpperCAmelCase = 0 print...
152
1
"""simple docstring""" from __future__ import annotations lowercase__ : Optional[int] = list[tuple[int, int]] lowercase__ : List[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0]...
224
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType S...
46
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFea...
364
'''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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_ou...
322
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils impo...
69
"""simple docstring""" def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase = False ) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False ...
69
1
def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ): snake_case : Dict = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def ...
10
import fire from utils import calculate_rouge, save_json def UpperCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Tuple=None , **__lowerCamelCase : Tuple ): snake_case : Optional[Any] = [x.strip() for x in ...
10
1
'''simple docstring''' from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCol...
297
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
53
0
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" assert column_title.isupper() lowercase_ : Dict = 0 lowercase_ : Tuple = len(__SCREAMING_SNAKE_CASE ) - ...
364
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Any = logging.get_logger(__name__) _lowercase : Dict = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/con...
264
0
import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer UpperCAmelCase_ :...
32
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_...
32
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tes...
371
from typing import List from .keymap import KEYMAP, get_character def __lowerCAmelCase ( a__ ) -> List[str]: def decorator(a__ ): __a = getattr(a__ , '''handle_key''' , [] ) handle += [key] setattr(a__ , '''handle_key''' , a__ ...
33
0
"""simple docstring""" import baseaa def lowerCAmelCase_ ( snake_case_ : str ) ->bytes: return baseaa.aaaencode(string.encode('utf-8' ) ) def lowerCAmelCase_ ( snake_case_ : bytes ) ->str: return baseaa.aaadecode(snake_case_ ).decode('utf-8' ) ...
126
"""simple docstring""" import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( 'split_dict' , [ SplitDict(), SplitDict({'train': SplitInfo(name='train' , num_bytes=1_3_3_7 ,...
126
1
import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVa...
201
def _A ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): if height >= 1: move_tower(height - 1 , __magic_name__ , __magic_name__ , __magic_name__ ) move_disk(__magic_name__ , __magic_name__ ) move_tower(height - 1 , __magic_name__ , __magic_name__ , __ma...
201
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''...
108
def _SCREAMING_SNAKE_CASE ( a , a ) -> list[int]: __A : Optional[int] = int(a ) # Initialize Result __A : Optional[int] = [] # Traverse through all denomination for denomination in reversed(a ): # Find denominations ...
280
0
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 OptionalDependencyNotAvaila...
50
from manim import * class _lowercase ( snake_case_ ): def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Any: """simple docstring""" UpperCamelCase_ : str = Rectangle(height=0.5 , width=0.5 ) UpperCamelCase_ : Optional[Any] ...
50
1
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list[list[float]]: """simple docstring""" A__ = [] for data in source_data: for i, el in enumerate(lowercase_ ): if len(lowercase_ ) < i + 1: d...
14
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...
313
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase_ ) class __snake_case ( lowerCamelCase_ ): # `task` is not a ClassVar since we want it to be part...
204
from __future__ import annotations __lowerCamelCase : Dict = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] __lowerCamelCase : Union[str, Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def __SCREAMING_SNAKE_CASE ( __UpperCamelCas...
204
1
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _UpperCamelCase ): @require_torch def __lowercase ( ...
89
'''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
1
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_...
367
def __a ( lowerCAmelCase_ : Dict ) -> Dict: '''simple docstring''' return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], ...
277
0
def lowerCAmelCase_ ( __a , __a , __a ) -> float: """simple docstring""" lowerCamelCase__: str =(num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowerCAmelCase_ ( ) -> List...
10
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __A = "." if __name__ == "__main__": __A = os.path.join(REPO_PATH, "utils/documentation_tests.txt") __A = [] ...
10
1
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets UpperCAmelCase__ = "\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\...
290
UpperCAmelCase__ = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } def A ( _UpperCAmelCase : dict , _UpperCAmelCase : Optional[int] , _Upper...
290
1
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 _A ( unittest.TestCase ): def _lowerCamelCase ( self : Tuple): '''simple ...
49
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ ...
91
0
'''simple docstring''' import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerc...
352
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowerCamelCase_ = logging.get_logger(__name__) class lowercase_ ( A ): """simp...
111
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch...
291
"""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
0
class SCREAMING_SNAKE_CASE__ : def __init__( self : str ): __snake_case : int = """""" __snake_case : Tuple = """""" __snake_case : List[str] = [] def snake_case__ ( self : Optional[Any] , _lowerCAmelCa...
20
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_blenderbot_small": [ "BLENDERBOT_SMALL_PRETRAINED_CONFIG_...
20
1
"""simple docstring""" _A = """Alexander Joslin""" import operator as op from .stack import Stack def a__ ( lowerCAmelCase ) -> int: UpperCAmelCase__ : Optional[Any] = {"""*""": op.mul, """/""": op.truediv, """+""": op.add, """-""": op.sub} UpperCAmelCase__ ...
171
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from ...
171
1
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> List[Any]: _U...
369
# 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 by ap...
189
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/L...
217
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_...
217
1
def __a ( lowerCAmelCase_ : int ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_= (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def __a ( lowerCAmelCase_ : int = 50_00 ) -> str: '''simple docstring''' ...
366
import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, Par...
277
0
from __future__ import annotations def _lowerCAmelCase (_lowerCAmelCase): # This function is recursive UpperCamelCase_ = len(_lowerCAmelCase) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: ...
128
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils...
128
1
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( _lowercase ) -> list: if len(_lowercase ) == 0: return [] UpperCAmelCase : Union[str, Any] = min(_lowercase ), max(_lowercase ) UpperCAmelCase : str ...
350
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: ...
338
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ : int = logging.get_logger(__name__) a_ : List[str] = {"""vo...
55
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case ...
55
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : str = {...
120
from __future__ import annotations UpperCAmelCase_ : Dict = [True] * 100_0001 UpperCAmelCase_ : Any = 2 while i * i <= 100_0000: if seive[i]: for j in range(i * i, 100_0001, i): UpperCAmelCase_ : Tuple = False i += 1 def SCREAMING_SNAKE_CASE_ ...
120
1
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class lowerCamelCase (SCREAMING_SNAKE_CASE__ ): """simple docstring"...
118
import math from datetime import datetime, timedelta def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = year % 1_9 SCREAMING_SNAKE_CASE_ = year % 4 SCREAMING_SNAKE_CASE_ = year % 7 SCREAMING_SNAKE_CASE_ = math.floor(year / 1_0_0 ) SCRE...
118
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization impor...
245
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): A_ :Any = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name:...
245
1
def _snake_case( SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A__ ...
7
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import requir...
308
0
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available __UpperCamelCase = ...
353
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MA...
13
0
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
# 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 by app...
20
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor UpperCAmelCase = logging.get_logger(__name__) class __magic_name__ ( __UpperCAmelCase ): def __init__( self : Dict ...
172
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testin...
172
1
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path SCREAMING_SNAKE_CASE__ = Path(__file__).resolve().parents[3] / """src""" sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa ...
325
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass...
325
1
"""simple docstring""" import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets _a : int = '\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual...
363
"""simple docstring""" from __future__ import annotations from typing import Any class _lowerCAmelCase : """simple docstring""" def __init__( self : Union[str, Any], UpperCAmelCase__ : int ): __lowercase = num_of_nodes __lowercase =...
144
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_distilbert': [ ...
249
"""simple docstring""" from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig a_ = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_p...
249
1
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float(moles / volume ) * nfactor ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (volume) ) ...
354
"""simple docstring""" from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatur...
182
0
"""simple docstring""" from typing import Any def lowercase__ ( snake_case_ :list ): if not input_list: return [] __UpperCAmelCase = [input_list.count(snake_case_ ) for value in input_list] __UpperCAmelCase = max(snake_case_ ) # Gets the maximum count ...
332
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule _lowercase : int = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys ...
332
1
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tens...
350
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class A( UpperCamelCase ): '''...
208
0
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar A__ : Optional[int] = TypeVar('T') class lowercase__ ( Generic[T] ): def __init__( self : Tuple , snake_case__ :...
144
"""simple docstring""" from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test...
173
0
import gc import unittest from transformers import CTRLConfig, 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 ModelTesterMix...
371
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, ) __A : List[Any] = { '''configuration_xlm_roberta'''...
323
0
"""simple docstring""" 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_to...
98
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils imp...
201
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : str = logging.get_logger(__name__) lowercase__ : str = { """google/pix2struct-textcap...
289
"""simple docstring""" def UpperCamelCase_ ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] ) -> None: """simple docstring""" lowerCAmelCase_ : List[Any] = len(lowerCAmelCase__ ) print('The followin...
289
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) UpperCamelCase__ = {"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig"...
92
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase : Union[str, Any] = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attenti...
13
0
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be check...
369
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: """simple docstring""" snake_case__ : Optional[int] = len(__lowerCAmelCase ) + 1 snake_case__ : Tuple = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where d...
44
0
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, pa...
252
"""simple docstring""" import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class lowercase_ ( nn.Module ): '''simple docstring''' UpperCAmelCase : int ...
315
0
import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class __a ( tf.keras.optimizers.schedules.LearningRateSchedule ): def __init...
369
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 TimmBackboneConfig ...
28
0
"""simple docstring""" import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, lo...
109
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax imp...
144
0
"""simple docstring""" import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging __SCREAMING_SNAKE_CASE : str = '\\n\n' __SCREAMING_SNAKE_CASE : Dict = '...
371
"""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 __SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) __...
233
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json""" ), """facebook/dpr-q...
73
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = { '''configuration_jukebox''': [ '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''JukeboxConfig''', '''Ju...
79
0
from sklearn.metrics import recall_score import datasets SCREAMING_SNAKE_CASE_ = '\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false n...
366
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoo...
189
0
import os def __lowerCamelCase ( ): """simple docstring""" lowercase__ : List[Any] = os.path.dirname(os.path.realpath(lowerCamelCase__ ) ) lowercase__ : int = os.path.join(lowerCamelCase__ , "triangle.txt" ) with open(...
130
"""simple docstring""" from ..utils import DummyObject, requires_backends class a ( metaclass=UpperCAmelCase__ ): UpperCamelCase : Optional[int] = ['torch', 'torchsde'] def __init__( self : Union[str, Any] , *lowerCAmelCase : Any , **lowerCAme...
173
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 __UpperCamelCase = ...
357
"""simple docstring""" import copy import re class UpperCamelCase : SCREAMING_SNAKE_CASE_ = "hp" SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = None @classmethod def a_ ( cls, lowerCAmelCase__, lowerCAmelCase__) ->...
312
0
"""simple docstring""" from manim import * class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = Rectangle(height=0.5 ,width=0.5 ) A = ...
74
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''...
74
1
"""simple docstring""" lowerCamelCase_ = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} lowerCamelCase_ = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def snake_case ( A__ ,A__ ,A__ ): UpperCAmelCase_ : Optional[Any] = True UpperCAmelCase_ ...
355
"""simple docstring""" import numpy as np def snake_case ( A__ ,A__ ,A__ ,A__ ,A__ ): UpperCAmelCase_ : Tuple = int(np.ceil((x_end - xa) / h ) ) UpperCAmelCase_ : Optional[Any] = np.zeros((n + 1,) ) UpperCAmelCase_ : ...
253
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A = { '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processi...
160
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A = { '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processi...
160
1
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) -> int: '''simple docstring''' if depth < 0: raise ValueError('Depth cannot be less than 0' ) if len(_Upp...
323
import math def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase = 100 ) -> int: '''simple docstring''' lowerCAmelCase : Any = sum(i * i for i in range(1, n + 1 ) ) lowerCAmelCase : str = int(math.pow(sum(range(1, n + 1 ) ), 2 ) ) return s...
323
1
'''simple docstring''' 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 Conf...
272
'''simple docstring''' from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig __lowercase = logging.get_logger(__name__) __lowercase = '''T5Config''' class a__( lowerCAmelCas...
272
1
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, ) __UpperCAmelCase : Tuple = {"configuration_xglm": ["XGL...
293
import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' ...
293
1
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters lowerCAmelCase__ = (720, 1280) # Height, Width lowerCAmelCase__ = (0.4, 0.6) # if height or width lower than this scale, drop it. lowerCAmel...
72
'''simple docstring''' from PIL import Image def __lowerCamelCase ( A__ , A__ ) -> Image: """simple docstring""" def brightness(A__ ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueEr...
28
0
'''simple docstring''' 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 VQDiffusion...
237
'''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 ( MaxLengthCriteria...
237
1
'''simple docstring''' 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 ...
3
UpperCAmelCase : dict[tuple[int, int, int], int] ={} def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase): # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: ...
128
0
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class _lowerCamelCase( _a ): lowercase_ : Tuple = (PNDMScheduler,) lowercase_ : str = (("""num_inference_steps""", 50),) def ...
84
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 ): def UpperCamelCase ( self) -> Tuple: ...
84
1
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import ...
19
'''simple docstring''' lowerCamelCase : 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" low...
47
0
"""simple docstring""" import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging snake_case_ = logging.get_logger(__name__) def _lowerCAmelCase ( lowercase_ ): Uppe...
181
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _lowerCAmelCas...
181
1
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def A_ ( A__ ) -> float: return np.dot(A__ , A__ ) class A__ : """simple docstring""" def __init__( self , *, lowercase = np.inf , lowercas...
99
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __...
347
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class A ( unittest.TestCase ): ""...
282
import unittest from typing import Dict, List, Optional, Union 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...
282
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__ : Any = { 'configuration_electra': ['ELECTRA_PRETR...
144
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. __lowercase = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller th...
43
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 lowerCAmelCase__ ( UpperCamelCase__ , ...
365
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { 'configuration_vision_encoder_decoder': ['Vision...
324
0
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def A ( _UpperCAmelCase : str = "isbn/0140328726" ) -> dict: '''simple docstring''' _UpperCAmelCase = olid.strip().strip('/' ) # Remove leading/trailing white...
339
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase__ = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and...
339
1
'''simple docstring''' import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str...
264
'''simple docstring''' import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings _lowe...
264
1
"""simple docstring""" def __UpperCAmelCase ( __lowerCamelCase ) -> int: lowercase__ : Optional[Any] = 1 for i in range(1 , num + 1 ): fact *= i return fact def __UpperCAmelCase ( __lowerCamelCase ) -> int: ...
16
from abc import ABC, abstractmethod from argparse import ArgumentParser class snake_case_ (lowerCamelCase_ ): @staticmethod @abstractmethod def lowerCamelCase__( __snake_case :ArgumentParser ) -> Dict: raise NotImplementedError() @abstractme...
240
0
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_available, is_vi...
60
# 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 requ...
60
1
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class lowerCAmelCase_ ( A__ ): '''simple docstring''' def __init__( self , ...
301
"""simple docstring""" import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calcula...
301
1
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib lowerCamelCase ...
196
import argparse import os import re import packaging.version lowerCamelCase : Optional[Any] ='''examples/''' lowerCamelCase : List[Any] ={ '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), ...
196
1