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 operator as op a = '''scaler.pt''' a = '''pytorch_model''' a = '''random_states''' a = '''optimizer''' a = '''scheduler''' a = '''pytorch_model.bin''' a = '''pytorch_model.bin.index.json''' a = '''model.safetensors''' a = '''mod...
315
"""simple docstring""" from collections.abc import Callable def _snake_case ( _snake_case : Callable[[float], float] , _snake_case : float , _snake_case : float ) -> float: '''simple docstring''' _A = a _A ...
315
1
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import Tokenizer...
114
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transfor...
114
1
'''simple docstring''' import logging from transformers.configuration_utils import PretrainedConfig a__ : Union[str, Any] = logging.getLogger(__name__) class lowercase_ ( a__ ): __UpperCAmelCase = 'masked_bert' def __init__( self , a=3_05_22 , a=...
80
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, re...
38
0
from datetime import datetime as dt import os from github import Github UpperCamelCase = [ """good first issue""", """good second issue""", """good difficult issue""", """feature request""", """new model""", """wip""", ] def _SCREAMING_SNAKE_CASE ( ): A_ : str ...
365
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" snake_case = ["image_processor", "tokenizer"] snake_case = "CLIPI...
65
0
def _SCREAMING_SNAKE_CASE ( lowercase : Optional[Any]=2_81_23 ): '''simple docstring''' lowerCamelCase_ = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + ...
204
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase : str = { "configuration_nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"], } try: if not is_torch_available()...
204
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, Ber...
39
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 SCREAMING_SNAKE_CASE__ ( UpperCamelCas...
39
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 Conf...
70
'''simple docstring''' import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ...
208
0
"""simple docstring""" import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPV...
366
"""simple docstring""" import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffuse...
241
0
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : int =int(number**0.5 ) return number == sq * sq def _A ( SCREAM...
95
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ...
95
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _SCREAMING_SNAKE_CASE = {"configuration_vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"]} try: if not is_torch_availa...
3
'''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.or...
3
1
"""simple docstring""" 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 l...
25
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"""configuration_mbart""": ["...
58
0
import enum import shutil import sys UpperCamelCase__ , UpperCamelCase__ = shutil.get_terminal_size() UpperCamelCase__ = {"""UP""": """A""", """DOWN""": """B""", """RIGHT""": """C""", """LEFT""": """D"""} class a__ ( enum.Enum ): _a : Any = 0 _...
102
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex UpperCamelCase__ = logging.getLogger(__name__) class a__ : def __init__( self ): """s...
102
1
"""simple docstring""" def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): def update_area_of_max_square(_snake_case ,_snake_case ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 SCREAMING_SNA...
25
"""simple docstring""" def lowercase_ ( _snake_case ): if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(_snake_case ,_snake_case ): raise TypeError("""Input value must be a 'int' type""" ) ...
25
1
import numpy as np import qiskit def __UpperCamelCase ( _A : int = 8 , _A : int | None = None ) ->str: """simple docstring""" lowerCamelCase_ =np.random.default_rng(seed=_A ) # Roughly 25% of the qubits will contribute to the key. ...
49
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A : List[Any] = logging.get_logger(__name__) __A : List[Any] = [ ['attention', 'attn'], ['encoder_attention'...
49
1
import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipeli...
313
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params ...
313
1
"""simple docstring""" 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, ...
24
"""simple docstring""" import logging import os import threading import time try: import warnings except ImportError: SCREAMING_SNAKE_CASE : Tuple = None try: import msvcrt except ImportError: SCREAMING_SNAKE_CASE : List[str] = None try: import fcntl except ImportError: SC...
24
1
from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : str = logging.get_logger(__name__) A__ : Any = { 'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json', } class _UpperCAmelCase ( A__ ):...
207
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def a ( lowerCamelCase_ ): '''simple docstring''' lowercase__ = [] lowercase__ = [] lowercase__ = [] for ...
207
1
import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, Traini...
371
from __future__ import annotations __lowerCamelCase : Tuple = list[list[int]] # assigning initial values to the grid __lowerCamelCase : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0...
204
0
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, Tuple import numpy as np ...
71
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for t...
80
0
'''simple docstring''' def __magic_name__( ): return [ a * b * (1_0_0_0 - a - b) for a in range(1, 9_9_9) for b in range(lowerCamelCase, 9_9_9) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(f"""{so...
9
'''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...
9
1
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging a__: str = logging.get_logger(__name__) def UpperCamelCase__( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : st...
193
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = (DDIMParallelScheduler,) __SCREAMING_SNAKE_CASE = (('''eta''', 0.0)...
193
1
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> list[int]: # This function is recursive a = len(__UpperCamelCase) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= ...
180
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerc...
180
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_...
10
'''simple docstring''' import warnings from ..trainer import Trainer from ..utils import logging __a = logging.get_logger(__name__) class A__ ( UpperCamelCase ): """simple docstring""" def __init__( self : Optional[int] , lowerCAmelCase__ : ...
145
0
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class __snake_case ( nn.Module ): def __init__( self : Any , _lowercase : Any = 16 , _lowercase : List[Any] = 88 , ...
355
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch ...
204
0
import math import random from typing import Any from .hill_climbing import SearchProblem def __snake_case ( _UpperCAmelCase , _UpperCAmelCase = True , _UpperCAmelCase = math.inf , _UpperCAmelCase = -math.inf , _UpperCAmelCase = math.inf , _UpperCAmelCase = -math.inf , _UpperCAmelCase = Fal...
49
'''simple docstring''' def UpperCAmelCase_ ( __lowercase : str ) -> str: '''simple docstring''' return " ".join( "".join(word[::-1] ) if len(__lowercase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": im...
22
0
'''simple docstring''' from typing import Any def __magic_name__ ( A ) -> list[Any]: if not input_list: return [] snake_case = [input_list.count(A ) for value in input_list] snake_case = max(A ) # Gets the maximum count in the input list. # Gets values of...
332
'''simple docstring''' import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing...
332
1
from collections import deque class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : int = process_name # process name __A : Union[str, Any] = arrival_time # arrival time of the process ...
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_...
280
1
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( """The `inpainting.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionInpaintPipeline` instead.""" )
358
from __future__ import annotations from statistics import mean def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> list[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ = [0] * no_of_processes SCREAMING_SNAKE_CASE__ ...
169
0
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available ...
252
'''simple docstring''' import json from typing import 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 .toke...
223
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2,...
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingfac...
0
1
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: lowerCAmelCase__ : Union[str, Any] ...
242
"""simple docstring""" from string import ascii_uppercase _A = {str(ord(c) - 5_5): c for c in ascii_uppercase} def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase ) -> str: if isinstance(__UpperCAmelCase , __UpperCAmelCase ): raise TypeEr...
242
1
"""simple docstring""" def _A (__a = 10 , __a = 22 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = range(1 , __a ) SCREAMING_SNAKE_CASE_ : Tuple = range(1 , __a ) return sum( 1 for powe...
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "SpeechT5FeatureExtractor" __UpperCamelCase = "SpeechT5Tokenizer" def __init__( ...
318
1
"""simple docstring""" from __future__ import annotations def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = len(UpperCamelCase_ ) - 1 while i < j: if nums[i] + nums[j] == target: return [i,...
100
from math import sqrt def lowerCAmelCase ( lowerCAmelCase_ )-> bool: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and ( number >= 0 ), "'number' must been an int and positive" lowerCAmelCase_ : List[Any] = True # 0 and 1 are ...
262
0
"""simple docstring""" from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageI...
12
"""simple docstring""" # 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 lowercase__ = Path(__file__).resolve().parents[3] / """src""" sys.path.insert(1, str(git_repo_path))...
12
1
"""simple docstring""" from math import isqrt def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> list[int]: '''simple docstring''' lowercase_ = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: ...
136
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Tuple = {"configuration_plbart": ["PLBART_PRETRAI...
136
1
"""simple docstring""" import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvi...
368
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> list[int]: a = 2 a = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(__UpperCamelCase) if n...
180
0
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.sc...
44
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet....
44
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging __UpperCAmelCase = logging.get_logger(__name__) _...
367
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__)...
42
0
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase__ = get_tests_d...
290
"""simple docstring""" def __a ( _SCREAMING_SNAKE_CASE = 1000000 ) ->int: a__: int = limit + 1 a__: Optional[int] = [0] * limit for first_term in range(1 , _SCREAMING_SNAKE_CASE ): for n in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SN...
290
1
"""simple docstring""" import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): lowercase__ = (EulerDiscreteScheduler,) lowe...
313
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD ...
313
1
'''simple docstring''' def _A ( snake_case ) -> List[str]: for i in range(len(snake_case ) - 1 , 0 , -1 ): _lowercase : Tuple = False for j in range(snake_case , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: _lowerc...
250
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ...
81
0
"""simple docstring""" import argparse import os import re _UpperCamelCase : int = 'src/transformers' # Pattern that looks at the indentation in a line. _UpperCamelCase : Union[str, Any] = re.compile(r'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. _Upper...
350
"""simple docstring""" import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _UpperCamelCase : int = get_test...
186
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...
136
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Tuple = {"configuration_plbart": ["PLBART_PRETRAI...
136
1
"""simple docstring""" import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import...
24
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArg...
24
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging...
270
def UpperCAmelCase_ ( __lowerCAmelCase ) -> int: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) __lowercase : List[str] = 0 while number: # This way we arrive at n...
156
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo _snake_case = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schus...
300
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor _snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( a): def __init__( self, *__a, **__a): '''simple docstring''' warnings....
300
1
def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_): # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for ver...
149
from ..utils import DummyObject, requires_backends class _a ( metaclass=UpperCamelCase__): """simple docstring""" UpperCamelCase__ = ["""flax""", """transformers"""] def __init__( self: Optional[int] , *__lowerCamelCase: ...
149
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) snake_case : Tuple = { '''configuration_mega''': ['''MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegaConfig''', '''MegaOnnxConfig'''], } try: if not is_torch...
353
from ...configuration_utils import PretrainedConfig class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = 'bert-generation' def __init__( self , _lowerCamelCase=5_0358 , _lowerCamelCase=1024 , _lowerCamelCase=24 , _lowerCamelCase=16 , _lowerCamelCase=4096 , _lowerCamelCase="g...
281
0
'''simple docstring''' import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) a : Tuple = logging.getLogger() ...
311
'''simple docstring''' import argparse import copy def lowercase ( __magic_name__ ): '''simple docstring''' UpperCAmelCase : List[str] = {} with open(__magic_name__ ) as f: for line in f: if line.split()[0] not in dict_...
311
1
def lowerCAmelCase_ ( _lowercase : list[int]) -> int: """simple docstring""" if not numbers: return 0 if not isinstance(_lowercase , (list, tuple)) or not all( isinstance(_lowercase , _lowercase) for number in numbers): ...
266
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case__ (ctypes.Structure ): """simple docstring""" __lowerCAmelCase :Dict = [("size", c...
266
1
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _lowerCAmelCase : List[str] = logging.get_logger(__name__) class __magic_name__ ( lowerCAmelCase_ ): def __init__( self , *__snake_case , **__snak...
218
"""simple docstring""" def _snake_case ( lowercase__ ): if not isinstance(lowercase__ , lowercase__ ): raise ValueError('Input series is not valid, valid series - [2, 4, 6]' ) if len(lowercase__ ) == 0: raise ValueError('Input list must be a non ...
96
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 ...
357
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging _lowerCamelCase : List[Any] = logging.get_logger(__name__) def __a ( UpperCAmelCase ) ->List[int]: """simple docstring""" if isin...
337
0
from collections import deque from math import floor from random import random from time import time class __lowerCAmelCase : """simple docstring""" def __init__( self ) -> str: '''simple docstring''' __lowerCamelCase ...
90
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids...
90
1
"""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, TrainingJobAnalytics from sa...
361
"""simple docstring""" import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditio...
30
0
"""simple docstring""" import argparse from collections import defaultdict import yaml __UpperCAmelCase = 'docs/source/en/_toctree.yml' def _snake_case ( lowercase__ : Any ) -> Any: '''simple docstring''' lowerCAmelCase_ :Any ...
84
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_C...
84
1
"""simple docstring""" import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated __snake_case = collections.namedtuple('''_Dataset...
370
"""simple docstring""" import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test...
153
0
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths,...
65
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .sched...
179
0
"""simple docstring""" import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_conf...
314
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging snake_case__ : List[str] = logging.get_logger(__name__) class snake_case_( a__ ): ...
314
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A ={ 'configuration_pix2struct': [ 'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Pix2StructConfig', 'Pix2StructT...
34
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, r...
279
0
import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from tr...
200
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_u...
200
1
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_toke...
292
"""simple docstring""" # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to...
292
1
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_m...
10
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor __lowerCamelCase = logging.get_logger(__name__) class UpperCAmelCase ( A_ ): def __init__(self : List[Any] , *snake_case__ : List[str] , **snake_...
10
1
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast snake_case_ = datasets.utils.logging.get_logger(__name__) @dataclass class SCREAMING_SNAKE_CA...
24
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" A__ = args.pruning_method A__ = ar...
14
0
'''simple docstring''' import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class UpperCamelCase_ : lowercase = None lowercase = False lowercase = False lowercase = False lowercase ...
338
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule a : Optional[int] = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: ...
338
1
import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentPars...
204
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _a ( lowerCAmelCase): ...
260
0
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
60
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): ...
60
1
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def ...
85
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.s...
123
0
"""simple docstring""" import os 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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCas...
310
"""simple docstring""" import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowercase__ ( l...
310
1
class _UpperCamelCase : """simple docstring""" def __init__( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' __lowercase = val __lowercase = None __lowercase = None def _SCREAMING_SN...
210
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __a : Any = { """configuration_bloom""": ["""BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BloomConfig""", """BloomOnnxConfig"""], } try: if not is_tokenizers_...
210
1
'''simple docstring''' import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _lowerCamelCase : int = c...
351
'''simple docstring''' 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 TFMod...
249
0
'''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
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test...
167
0
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 lowercase__ ( UpperCamelCase_ , UpperCamelCase_): @register_to_config d...
258
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class lowercase__ ( UpperCamelCase_): Up...
258
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging lowerCAmelCase : str = logging.get_logger(__name_...
13
import unittest from transformers import LiltConfig, 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 ModelTesterMixin, id...
36
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''], '''tokenization_canine''': ['''CanineTokenizer'''],...
354
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_torch_available(): import torch i...
278
0
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class a ( lowerCAmelCase_ ): U...
173
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils....
238
0
"""simple docstring""" def lowercase ( A_ , A_ )-> Optional[int]: '''simple docstring''' _validate_point(lowercase__ ) _validate_point(lowercase__ ) if len(lowercase__ ) != len(lowercase__ ): raise ValueError("Both points must be in the same n-d...
363
"""simple docstring""" import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerato...
226
0
from ....configuration_utils import PretrainedConfig from ....utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": ( "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/reso...
275
def _lowercase ( lowercase__ , lowercase__ ): return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def _lowercase ( lowercase__ , lowercase__=0 ): return sorted(lowercase__ , key=lambda lowercase__ : x[column] ) def _lowercase ( lower...
275
1
from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch ...
366
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_ten...
286
0
from __future__ import annotations def a__ ( UpperCAmelCase : list[int] , UpperCAmelCase : list[int] , UpperCAmelCase : int ) -> tuple[float, list[float]]: UpperCAmelCase : str = list(range(len(UpperCAmelCase ) ) ) UpperCAmelCase : List...
336
import numpy # List of input, output pairs _lowerCamelCase : Dict = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) _lowerCamelCase : str = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) _lowerCame...
336
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require...
199
'''simple docstring''' from timeit import timeit def _A ( snake_case ) -> int: if number < 0: raise ValueError("the value of input must not be negative" ) _lowercase : Union[str, Any] = 0 while number: number &= number - 1 result += 1 ...
199
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class A_ ( unittest.TestCase ): '''simpl...
333
def __a ( ) -> list[list[int]]: '''simple docstring''' return [list(range(1_0_0_0 - i , -1_0_0_0 - i , -1 ) ) for i in range(1_0_0_0 )] A_ : Union[str, Any] = generate_large_matrix() A_ : Union[str, Any] = ( [[4,...
333
1
import argparse import math import traceback import dateutil.parser as date_parser import requests def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = {} __A = job["started_at"] __A = job["completed_at"] ...
124
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split SCREAMING_SNAKE_CASE :Tuple = datasets.load_iris() SCREAMING_SNAKE_CASE :Dict = np.array(data['data']) SCREAMING_SNAKE_CASE :Optional[int] ...
124
1
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, Rea...
143
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging....
143
1
'''simple docstring''' 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 PaddingStrate...
332
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { "configuration_git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitVisionConfig"], "processing_git": ["GitProcessor"], } try: ...
332
1
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __UpperCamelCase ( lowerCAmelCase__ ): """simple docs...
303
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __UpperCamelCase ( lowerCAmelC...
303
1
"""simple docstring""" import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return d...
363
from __future__ import annotations import os from collections.abc import Mapping UpperCamelCase__ : Any = tuple[int, int] class lowerCamelCase_ : def __init__( self : Optional[Any] ,__lowerCamelCase : set[int] ,__lowerCamelCase ...
330
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available snake_case__ : Optional[int] = { '''configuration_altclip''': [ '''ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''A...
60
import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.ba...
130
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCamelCase ( metaclass=lowerCamelCase_ ): lowercase = ["""transformers""", """torch""", """note_seq"""] def __init__( self ,*__UpperCamelCase ,**__UpperCamelCase ) -> str: ...
367
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase ( unittest.Te...
321
0
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...
147
"""simple docstring""" from math import isqrt, loga def _snake_case ( UpperCamelCase : int ): UpperCAmelCase : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , UpperCamelCase , UpperCamelCase ...
109
0
'''simple docstring''' import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_ava...
359
'''simple docstring''' import math import sys def SCREAMING_SNAKE_CASE__( _UpperCamelCase : str ) -> str: '''simple docstring''' UpperCamelCase__ = "" try: with open(_UpperCamelCase , "rb" ) as binary_file: UpperC...
31
0
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def ...
53
def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]: if index == r: for j in range(SCREAMING_SNAKE_CASE__ ): prin...
20
0
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a__( lowerCamelCase__ ): lowercase__ = ["""image_processor""", """tokenizer"""] lowercase__ = """CLIPImageProcessor""" lowercase__ ...
362
'''simple docstring''' import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, Character...
96
0
"""simple docstring""" 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, prepa...
77
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __a : Optional[int] = logging.get_logger(__name__) __a : Tuple = { """facebook/data2vec-text-base""": """https://...
210
0
import numpy as np from PIL import Image def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> np.ndarray: lowercase__ = np.array(_SCREAMING_SNAKE_CASE ) if arr.shape[0] != arr.shape[1]: raise ValueError...
269
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( ...
269
1
"""simple docstring""" from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge __UpperCamelCase : Tuple = [ '''Prosecutor: "No videos were used in the crash investigation" German paper...
106
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __UpperCamelCase : str = { '''configuration_longt5''': ['''LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LongT5Config''', '''Long...
106
1
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar lowerCAmelCase_ : int = TypeVar('''T''') class __lowerCAmelCase ( Generic[T] ): snake_case : deque[T] # C...
366
'''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 __A ( lowerCAmelCase_ , lowerCAmelCas...
170
0
'''simple docstring''' import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ ( __lowercase : Union[str, Any] , __low...
22
"""simple docstring""" def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> int: def count_of_possible_combinations(__UpperCAmelCase ) -> int: if target < 0: return 0 if target == 0: r...
242
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase: int = logging.get_logger(__name__) lowerCAmelCase: List[Any] = { ...
96
'''simple docstring''' import argparse import os import re import packaging.version lowerCAmelCase: List[str] = 'examples/' lowerCAmelCase: List[Any] = { 'examples': (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), 'init': (re...
96
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from d...
280
import colorsys from PIL import Image # type: ignore def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: __A : List[str] = x __A : str = y for step in range(a ): # noqa: B007 __A : Union[str, Any] = a * ...
280
1
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataC...
261
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
1