code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransf...
16
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig _UpperCAmelCase : Dict ={ """susnato/ernie-m-base_pytorch""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json""", """susnato/ernie-m-large_pytorch""": """https...
262
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, D...
300
from __future__ import annotations from typing import Any class UpperCAmelCase_ : def __init__( self, __a, __a, __a = 0): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : int = row, column _...
300
1
import re def a_ ( _A ) -> bool: """simple docstring""" snake_case__ = re.compile( R'^(?:0|94|\+94|0{2}94)' R'7(0|1|2|4|5|6|7|8)' R'(-| |)' R'\d{7}$' ) return bool(re.search(_A , _A ) ) if __name__ == "__main...
307
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : int = logging.get_logger(__name__) __UpperCamelCase : List[Any] = { """tanreinama/GPTSAN-2.8B-spout_is_uniform""": ( """https://huggingface.co/tanreinama...
307
1
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def __UpperCamelCase ( lowerCAmelCase__ : dict ): return (data[...
90
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer lowercase__ =logging.get_logger(__name__) lowercase__ ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', ...
90
1
"""simple docstring""" import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase_ = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:])...
16
"""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_ = 4 lowerCAmelCase_ = 3 cla...
16
1
import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase_ : def __init__( self : Optional[int] , A__ : List[str] ) -> Tuple: _snake_case = data _snake_case = [0X6_7_4_5_2_3_0_1, 0XE_F_C...
364
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependenc...
278
0
import os import string import sys A_ : Tuple = 1 << 8 A_ : List[Any] = { 'tab': ord('\t'), 'newline': ord('\r'), 'esc': 27, 'up': 65 + ARROW_KEY_FLAG, 'down': 66 + ARROW_KEY_FLAG, 'right': 67 + ARROW_KEY_FLAG, 'left': 68 + ARROW_KEY_FLAG, 'mod_int': ...
192
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_te...
61
0
from __future__ import annotations import queue class _UpperCAmelCase : """simple docstring""" def __init__( self : Optional[Any] , lowerCAmelCase_ : Tuple ) -> Optional[int]: __lowerCAmelCase = data __lowerCAmelCase = None __l...
207
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils imp...
207
1
def __snake_case ( _lowerCAmelCase : list ) -> int: if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information" ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] A_ : Optional[int] ...
300
def __snake_case ( _lowerCAmelCase : list ) -> list: if len(_lowerCAmelCase ) <= 1: return [tuple(_lowerCAmelCase )] A_ : Tuple = [] def generate(_lowerCAmelCase : int , _lowerCAmelCase : list ): A_ : List[str] = [0]...
300
1
def _lowerCamelCase( lowercase__ ) -> list: '''simple docstring''' def merge(lowercase__ , lowercase__ ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right ...
361
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCAmelCase = False class A ( unittest.TestCase ): pass @...
304
0
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common impo...
90
def lowerCamelCase_ ( UpperCamelCase__ : int ) -> bool: """simple docstring""" return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
90
1
from __future__ import annotations def lowerCamelCase__ ( A__ : list[int] , A__ : list[int] , A__ : int ): '''simple docstring''' __lowerCamelCase = list(range(len(A__ ) ) ) __lowerCamelCase = [v / w for v, w in zip(A__ , ...
29
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_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'hustvl/yolos-smal...
29
1
'''simple docstring''' from math import loga def SCREAMING_SNAKE_CASE( __lowercase ) -> Union[str, Any]: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(_A , _A ): raise TypeError('''Input ...
319
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def __UpperCamelCase ( _A ): lowerCAmelCase_ = 384 ...
278
0
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils impor...
89
'''simple docstring''' 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, ...
89
1
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def a ( *lowerCamelCase_ ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): lowercase__ = list(lowerCamelCase_ ) ...
207
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, requ...
207
1
"""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 U. We...
203
"""simple docstring""" import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_model...
203
1
import math from datetime import datetime, timedelta def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int ) -> datetime: """simple docstring""" SCREAMING_SNAKE_CASE__ = year % 19 SCREAMING_SNAKE_CASE__ = year % 4 SCREAMING_S...
219
'''simple docstring''' from __future__ import annotations def __UpperCAmelCase ( A : list , A : int , A : int , A : int ) -> list: UpperCAmelCase_ : Any = [] UpperCAmelCase_ , UpperCAmelCase_ : Tuple = input_list[low:mid...
304
0
"""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 ...
365
"""simple docstring""" import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor A__ : str = logging.get_logger(__name__) class lowercase__ ( snake_case__ ): def __init__( self : Optional[Any] , *snak...
209
0
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowercase__ ( __snake_case : Dict ): '''simple docstring''' UpperCAm...
29
def lowercase__ ( __snake_case : Dict ): '''simple docstring''' if not head: return True # split the list to two parts UpperCAmelCase_ , UpperCAmelCase_ : Any = head.next, head while fast and fast.next:...
29
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCAmelCase : Dict =logging.get_logger(__name__) class a_ ( A__ ): def __init__( self : Optional[int] , *lowercase : Dict , **...
351
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_...
147
0
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transfor...
89
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: ...
89
1
"""simple docstring""" def lowercase__ ( snake_case_ :int ): __UpperCAmelCase = 1 for i in range(1 , num + 1 ): fact *= i return fact def lowercase__ ( snake_case_ :int ): __UpperCAmelCase = 0 while number > 0: __UpperCAmelCase ...
361
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar _lowercase : List[Any] = TypeVar('T') class _UpperCAmelCase ( Generic[T] ): a__ : deque[T] # Cache store of keys a__ : s...
86
0
"""simple docstring""" def __lowerCAmelCase ( lowercase : list[int] ) -> float: """simple docstring""" if not nums: # Makes sure that the list is not empty raise ValueError("List is empty" ) snake_case : List[str] = sum(lowercase ) / len(lowerca...
203
"""simple docstring""" import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBe...
203
1
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and no...
189
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = [ ['attention', 'attn'], ['enco...
189
1
"""simple docstring""" def _snake_case ( UpperCamelCase : int , UpperCamelCase : Any ): return int((input_a, input_a).count(1 ) != 0 ) def _snake_case ( ): assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , ...
109
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import tor...
209
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class lowercase__ ( lowercase ): @staticmethod @abstractmethod def UpperCamelCase_ ( lowerCamelCase__ : ArgumentParser ): '''simple docstring''' raise...
236
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case_ : Optional[int] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerCo...
236
1
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, ...
147
import os # Precomputes a list of the 100 first triangular numbers a : Optional[Any] = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowerCAmelCase_ (): """simple docstring""" UpperCAmelCase_: Any = os.path.dirname(os.path.real...
147
1
import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoade...
365
"""simple docstring""" import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: ...
30
0
def UpperCAmelCase ( lowercase , lowercase ): """simple docstring""" def get_matched_characters(lowercase , lowercase ) -> str: __lowercase = [] __lowercase = min(len(_stra ) , len(_stra ) ) // 2 ...
210
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class A__ ( enum...
86
0
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class a_ ( snake_case_ ): '''simple docstring''' @staticmethod @abstractmethod def a__ (lowerCamelCase_ ): '''simple docstring''' raise NotImp...
316
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class a_ ( snake_case_ ): '''simple docstring''' @staticmethod @abstractmethod def a__ (lowerCamelCase_ ): '''simple docstring''' raise NotImp...
316
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class __a ( datasets.BeamBasedBuilder ): def __lowercase ...
189
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar lowerCamelCase : int =TypeVar('''T''') class __a ( Generic[T] ): _lowerCAmelCase : deque[T] # Cache store of keys _lowerCAmelCase ...
189
1
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils impo...
180
import math def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes ...
180
1
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class __lowerCAmelCase ( datasets.BuilderConfig): _a = None class __lowerCAmel...
236
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _UpperCAmelCase : List[str] = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CON...
236
1
import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) lowercase_ = logging.getLogg...
351
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: lowercase__ = [ 'encoder.version', 'decoder.version', 'm...
269
0
"""simple docstring""" from collections.abc import Callable def A_ ( _lowerCAmelCase : Callable[[float], float], _lowerCAmelCase : float, _lowerCAmelCase : float ): """simple docstring""" _a = a _a = b if function(snake_case__ ) == 0: ...
320
import argparse import os import re __a = 'src/transformers/models/auto' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict __a = re.compile(r'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict') # re pattern t...
30
0
from __future__ import annotations from typing import Any class A : """simple docstring""" def __init__( self : int,lowercase_ : int,lowercase_ : int,lowercase_ : float = 0 )-> None: '''simple docstring''' A__ ...
353
import datasets from .evaluate import evaluate lowercase_ = "\\n@inproceedings{Rajpurkar2016SQuAD10,\n title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n booktitle={EMNLP},\n year={2016}\n}\n" l...
282
0
"""simple docstring""" # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position UpperCamelCase : Dict = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3...
316
"""simple docstring""" def A ( snake_case :int , snake_case :int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
316
1
def a( A : int ) -> bool: """simple docstring""" if not isinstance(_snake_case , _snake_case ): a = f'''Input value of [number={number}] must be an integer''' raise TypeError(_snake_case ) if number < 0: return False a = num...
352
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _lowercase ( lowerCAmelCase ): """simple docstring""" __A = ["image_processor", "tokenizer"] __A = "ViTImageProcessor" __A ...
71
0
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_...
180
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json', # See all BioGPT models a...
180
1
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available ...
33
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A : int = { 'configuration_mobilevit': ['MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileViTConfig', 'MobileViT...
33
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP...
38
"""simple docstring""" from ..utils import DummyObject, requires_backends class A__ ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = ['torch', 'torchsde'] def __init__( self: int , *_SCREAMING_SNAK...
269
0
import functools from typing import Any def _A ( _a : str , _a : list[str] ): """simple docstring""" if not isinstance(_lowerCamelCase , _lowerCamelCase ) or len(_lowerCamelCase ) == 0: raise ValueError("""the st...
370
"""simple docstring""" def _A ( _a : int ): """simple docstring""" A = abs(_a ) A = 0 while n > 0: res += n % 1_0 n //= 1_0 return res def _A ( _a...
77
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ...
31
import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow _lowerCamelCase : int = False class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple...
282
0
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class a ( UpperCAmelCase ): _lowercase = 4_2 try: if...
350
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class a ( UpperCAmelCase ): _lowercase = (PNDMScheduler,) _lowercase = (("num_inference_steps", 5_0),) def _UpperCAmelCase ( self , **A_...
189
0
'''simple docstring''' import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class A_ ( tf.keras.layers.Layer ): def __init__( se...
22
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() A_ :List[str] = [ '''word...
71
0
"""simple docstring""" import qiskit def _UpperCAmelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any] ) -> Union[str, Any]: _snake_case = qiskit.Aer.get_backend('''aer_simulator''' ) # Create a Quantum Circuit acting on the q register _snake_cas...
357
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, ...
40
0
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = ["image_processor", "tokenizer"] ...
33
"""simple docstring""" __A : Any = { '''Pillow''': '''Pillow''', '''accelerate''': '''accelerate>=0.11.0''', '''compel''': '''compel==0.1.8''', '''black''': '''black~=23.1''', '''datasets''': '''datasets''', '''filelock''': '''filelock''', '''flax''':...
33
1
'''simple docstring''' def UpperCAmelCase_ (__a : int ): """simple docstring""" if a < 0: raise ValueError('Input value must be a positive integer' ) elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError('Input value must be a \'int\' type' ) re...
353
'''simple docstring''' import sys def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" _a : List[str] = len(__a ) _a : Dict = [[0 for x in range(__a )] for x in range(__a )] _a : Union[str, Any] = [[0 for x in...
5
0
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _A ...
62
"""simple docstring""" import math import flax.linen as nn import jax.numpy as jnp def a_ ( _lowerCAmelCase : jnp.ndarray , _lowerCAmelCase : int , _lowerCAmelCase : float = 1 , _lowerCAmelCase : float = 1 , _lowerCAmelCase : float = 1.0E4 , _lowerCAmelCase : bool = False , _lo...
77
0
'''simple docstring''' from pathlib import Path import numpy as np from PIL import Image def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> np.ndarray: lowerCamelCase__ : Union[str, Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r +...
354
'''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 DDIMSc...
129
0
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, Be...
106
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) lowerCamelCase : ...
189
0
"""simple docstring""" import math class lowerCamelCase : def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = 0.0 UpperCamelCase : Dict = 0.0 for i in range(len(SC...
353
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict ...
27
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ : Dict = logging.get_logger(__name__) snake_case_ : int = ...
51
"""simple docstring""" class _A : """simple docstring""" def __init__( self : int , __UpperCAmelCase : int): a : Tuple = size a : Dict = [0] * size a : Optional[int] ...
40
0
import logging import os from .state import PartialState class _UpperCamelCase ( logging.LoggerAdapter ): @staticmethod def lowercase ( _SCREAMING_SNAKE_CASE: List[Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ ...
328
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = len(UpperCamelCase_ ) UpperCamelCase_ = len(matrix[0] ) UpperCamelCase_ = min(UpperCamelCase_ , UpperCamelCase_ ) for row in range(UpperCamelCase...
328
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str] =logging.get_logger(__name__) A__ : List[Any] ={ '''microsoft/markuplm-base''': '''https://huggingface.co/microsoft/markuplm-base/resolve/mai...
70
def UpperCAmelCase_ ( __snake_case ) -> str: """simple docstring""" _lowercase =0 # if input_string is "aba" than new_input_string become "a|b|a" _lowercase ='''''' _lowercase ='''''' # append each character + "|" in new_string for range(0...
5
0
'''simple docstring''' import warnings from typing import Any, Dict, 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 ...featu...
190
'''simple docstring''' def _lowerCAmelCase ( __snake_case : str ) -> str: __A : Optional[Any] = [0] * len(__snake_case ) __A : Dict = [] __A : Optional[int] = [1] * len(__snake_case ) for values in ...
190
1
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm im...
278
import gc import math import unittest import torch from diffusers import UNetaDModel from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin __sn...
129
0
import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class A_ : def __init__(self :List[Any] , _UpperCamelCase :int )-> Optional[int]: if is...
250
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case__ : ...
250
1
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import Array...
175
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): ...
27
0
import requests A : List[str] = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=""" def UpperCamelCase ( __magic_name__ : Any ) -> List[Any]: """simple docstring""" lowercase__ = requests.get(_NEWS_API + bb...
353
A : Union[str, Any] = [ (1_0_0_0, 'M'), (9_0_0, 'CM'), (5_0_0, 'D'), (4_0_0, 'CD'), (1_0_0, 'C'), (9_0, 'XC'), (5_0, 'L'), (4_0, 'XL'), (1_0, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def UpperCamelCase ( __mag...
146
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" _snake_case = ['image_processor', 'tokenizer'] _snake_case = 'AutoIm...
328
import math def A_ ( snake_case : int ) -> bool: '''simple docstring''' return math.sqrt(snake_case ) * math.sqrt(snake_case ) == num def A_ ( snake_case : int ) -> bool: '''simple docstring''' ...
328
1
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...
364
"""simple docstring""" import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, B...
313
0
'''simple docstring''' from scipy.stats import spearmanr import datasets lowercase__ : Any = ''' The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with...
190
'''simple docstring''' import math import qiskit def _lowerCAmelCase ( __snake_case : int = 1 , __snake_case : int = 1 , __snake_case : int = 1 ) -> qiskit.result.counts.Counts: if ( isinstance(__snake_case , __snake_case ) ...
190
1
'''simple docstring''' import os # Precomputes a list of the 100 first triangular numbers lowerCamelCase_ = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def SCREAMING_SNAKE_CASE_ ( ) -> str: _SCREAMING_SNAKE_CASE = os.path.dirname(os.path.realpath(__A ) ) _SCREAMING_SNAKE_C...
111
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str ) -> str: _SCREAMING_SNAKE_CASE = len(__A ) _SCREAMING_SNAKE_CASE = len(__A ) _SCREAMING_SNAKE_CASE = ( first_str_length if first_str_length > second_str_length else second_str_lengt...
111
1
'''simple docstring''' from argparse import ArgumentParser from . import BaseTransformersCLICommand def _A ( snake_case ) -> Dict: return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class a__ ( lowerCamelCase_ ): ...
250
'''simple docstring''' from __future__ import annotations def _A ( snake_case ) -> float: _lowercase : Optional[Any] = 0.00 _lowercase : Dict = 0 for resistor in resistors: if resistor <= 0: _lowercase : Union[str, Any] = F'''R...
250
1
'''simple docstring''' import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() _lowercase : Tuple = ...
360
'''simple docstring''' import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available fr...
91
0
'''simple docstring''' import math def UpperCAmelCase_ ( __lowercase : int ) -> bool: '''simple docstring''' return math.sqrt(__lowercase ) * math.sqrt(__lowercase ) == num def UpperCAmelCase_ ( __lowercase : int ) -> ...
22
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import...
146
0
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...
360
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging a : Tuple = logging.get_logger(__name__) a : Optional[Any] = { 'facebook/encodec_24khz': 'https://huggingface.co/facebo...
82
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision fr...
166
from abc import ABC, abstractmethod from typing import List, Optional class a_ ( a__ ): """simple docstring""" def __init__( self ) ->List[str]: # test for the above condition self.test() def __lowerCAmelCase ( self ...
313
0
'''simple docstring''' from __future__ import annotations def _lowercase ( __A ,__A ): '''simple docstring''' if partitions <= 0: raise ValueError("""partitions must be a positive number!""" ) if partitions > number_of_bytes: raise ValueErro...
359
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json ...
243
0
import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq._...
111
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase : Optional[int] = logging.get_logger(__name__) __UpperCAmelCase : Optional[int] ...
111
1
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _UpperCamelCase = get_tests_dir('''fixtures/test_sentencepiece_with_bytef...
357
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, XCLIPVisionConfig, ...
335
0
'''simple docstring''' import random from typing import Any def _lowerCAmelCase ( _UpperCamelCase : Dict ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): _SCREAMING_SNAKE_CASE =random.randint(0 , len(__a ) - 1 )...
47
"""simple docstring""" import argparse import collections import os import re 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_table.py UpperCAmelCase_ : Optional[int...
91
0
"""simple docstring""" import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassi...
352
"""simple docstring""" def a__ ( __lowercase , __lowercase ) -> float: _validate_point(__lowercase ) _validate_point(__lowercase ) if len(__lowercase ) != len(__lowercase ): raise ValueError("Both points must be in the same n-dimensional space" )...
163
0
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : str = {"""vocab_file"...
52
from __future__ import annotations import math def _UpperCAmelCase ( snake_case ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, ...
82
0
# 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 # # U...
350
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device a__: Union[str, Any] = False class SCREAMING_SNAKE_CASE_...
39
0
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Dict = [[0 for _ in range(__SCREAMING_SNAKE_CASE )] for _ in range(m + 1 )] for i in range(m +...
93
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class snake_case ...
243
0
from __future__ import annotations def A ( lowercase , lowercase ) -> list[int]: '''simple docstring''' UpperCamelCase = 0 UpperCamelCase = len(lowercase ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target...
110
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer...
110
1
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( 'kwargs, expected' , [ ({'num_shards': 0, 'max_num_jobs': 1}, []), ({'num_shards': 10, 'max_num_jobs': 1}, [range...
213
"""simple docstring""" def _snake_case ( UpperCAmelCase_ : Dict ): # noqa: E741 A__ = len(UpperCAmelCase_ ) A__ = 0 A__ = [0] * n A__ = [False] * n A__ = [False] * n def dfs(UpperCAmelCase_ : ...
335
0
"""simple docstring""" def lowerCamelCase ( _UpperCamelCase : float , _UpperCamelCase : float ) -> float: '''simple docstring''' if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(_UpperCa...
320
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Tuple = { 'configuration_electra': ['...
320
1
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsMo...
253
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) ...
163
0
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def snake_case ( A__ ,A__=False ): UpperCAmelCase_ : Optional[int] = OmegaConf.load(A__ ) if display: print(yaml.dump(O...
253
"""simple docstring""" import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class UpperCamelCase_ (unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( ...
253
1
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Tuple = 60_08_51_47_51_43 ) -> int: """simple docstring""" try: SCREAMING_SNAKE_CASE__ = int(__lowerCAmelCase ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or ...
219
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transfor...
39
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
117
import pprint import requests _A = 'https://zenquotes.io/api' def _UpperCAmelCase ( ): return requests.get(API_ENDPOINT_URL + '/today' ).json() def _UpperCAmelCase ( ): return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": _A ...
117
1
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 ( IM...
110
from __future__ import annotations from collections.abc import Iterator class _a : def __init__( self: List[str] , UpperCamelCase_: int ) -> None: """simple docstring""" lowercase__ = value ...
110
1
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compar...
146
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets impor...
146
1
"""simple docstring""" import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_...
320
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin ...
320
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 snake_case_ (unittest.TestCase ): def lowerCam...
109
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Tuple = logging.get_logger(__name__) snake_case : List[Any] = { '''snap-research/efficientformer-l1-300''': ( '''https://huggingface.co/snap-rese...
109
1
import math def A_ ( a ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [True] * n SCREAMING_SNAKE_CASE_ : Tuple = False SCREAMING_SNAKE_CASE_ : Dict = False SCREAMING_SNAKE_CASE_ : int = True ...
253
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 lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase : Any = ...
253
1
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp ...
354
lowerCAmelCase_ = 256 # Modulus to hash a string lowerCAmelCase_ = 100_0003 def lowerCamelCase_ ( lowerCAmelCase: str , lowerCAmelCase: str )-> bool: _snake_case : Optional[int] = len(lowerCAmelCase ) _snake_case : int = ...
260
0
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class ...
117
import heapq import sys import numpy as np snake_case__ : Tuple = tuple[int, int] class A_ : def __init__(self :Union[str, Any] )-> Union[str, Any]: __A = [] __A = set() def _lowerCAmelCas...
117
1
"""simple docstring""" from numpy import exp, pi, sqrt def lowercase__ ( lowercase_ ,lowercase_ = 0.0 ,lowercase_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__m...
361
"""simple docstring""" from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" _UpperCamelCase : Optional[Any] = ta...
310
0
# 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 a...
146
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import Bnb...
146
1
'''simple docstring''' 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 lowerCAmelCase_...
351
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=1_024 , __lowerCAmelCase=1_024...
322
0
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class ...
109
"""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
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import Auto...
359
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedTyp...
110
0
"""simple docstring""" 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 _a ( lowerCAmelCase , lowerCAmelCase): """simple docstring""" ...
260
"""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_see...
260
1
'''simple docstring''' def UpperCAmelCase_ (__a : str , __a : str ): """simple docstring""" _a : str = len(__a ) _a : Union[str, Any] = len(__a ) _a : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )...
358
'''simple docstring''' from functools import lru_cache @lru_cache def UpperCAmelCase_ (__a : int ): """simple docstring""" if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__"...
5
0
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import Ta...
274
def _A ( _lowercase ) -> list: """simple docstring""" def merge(_lowercase , _lowercase ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) ...
310
0
'''simple docstring''' from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __lowerCAmelCase = Lock() def UpperCAmelCase_ (__a : Union[str, Any] , __a : Optional[Any] , __a : Optional[int] ...
364
'''simple docstring''' from collections.abc import Generator from math import sin def UpperCAmelCase_ (__a : bytes ): """simple docstring""" if len(__a ) != 3_2: raise ValueError('Input must be of length 32' ) _a : Any = b'' for i in [3, 2, 1, 0]: ...
5
0