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
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, BlipaProcessor, BlipImageProc...
50
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> bool: """simple docstring""" return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def lowerCamelCase__ ( __snake_case ) -> bool: ...
194
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available snake_case_ = { '''configuration_altclip''': [ '''ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AltCLIPConfig''', '''AltCLIPTextConfig''...
216
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE__ (__snake_case ): _...
216
1
'''simple docstring''' import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput A__ : Dict ='''scheduler_confi...
70
"""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...
264
0
'''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 Accelerator from accelerate.state impo...
199
'''simple docstring''' import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from ...
199
1
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { 't5-small': 'ht...
16
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / d...
347
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowercase = logging.get_logger(__name__) lowercase = { """facebook/convnextv2-tiny-1k-224""": ...
350
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineO...
35
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['BartphoTokenize...
76
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @...
65
0
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format...
297
import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.tes...
297
1
def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: a = len(__lowerCamelCase ) a = len(__lowerCamelCase ) a = ( first_str_length if first_str_length > second_str_length else second_str_length ) a = [...
228
def __A ( __lowerCamelCase ) -> int: a = hex_num.strip() if not hex_num: raise ValueError("""No value was passed to the function""" ) a = hex_num[0] == """-""" if is_negative: a = hex_num[1:] try: a = int(__...
228
1
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_dataset...
213
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Dict = {"configuration_van": ["VAN_PRETRAINED_CONFIG_ARCHIVE_MAP", "VanConfig"]} try: if not is_torch_available(): ...
213
1
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-te...
313
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...fe...
26
0
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 i...
355
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Tuple: lowerCamelCase__ : Optional[int] = sorted(zip(_UpperCAmelCase , _UpperCAmelCase ...
45
0
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch lowercase__ : ...
328
'''simple docstring''' import argparse from collections import defaultdict def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _snake_case = f"""{fil...
341
0
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax impo...
363
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class UpperCAmelCase_ ( nn.Module ): def __init__( self : Optional[int] , snake_case_ : int = 16 , snake_case_ ...
230
0
from __future__ import annotations def lowerCamelCase__ ( _a = 4): SCREAMING_SNAKE_CASE : Optional[Any] = abs(_a) or 4 return [[1 + x + y * row_size for x in range(_a)] for y in range(_a)] def lowerCamelCase__ ( _a): return reverse_row(transpose(_a)) # OR.. transpo...
76
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkout...
76
1
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 0 for ch in input_str: SCREAMING_SNAKE_CASE = ord(_UpperCAmelCase) SCREAMING_SNAKE_CASE = pow(2 , _UpperCAmelCase) # If we already turned on bit for current character's unicode if b...
327
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption t...
327
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) lowerCAmelCase : str = { """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCR...
13
"""simple docstring""" import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCAmelCase__ : Optional[int] = [ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight...
98
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE :Any = { '''configuration_jukebox''': [ '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''JukeboxConfig''', ...
156
'''simple docstring''' from typing import Union import fire import torch from tqdm import tqdm def UpperCAmelCase_ ( __lowercase : str , __lowercase : str = "cpu" , __lowercase : Union[str, None] = None ) -> None: '''simple docstring''' ...
156
1
"""simple docstring""" from __future__ import annotations def _A ( UpperCamelCase_ : list) -> float: '''simple docstring''' if not nums: raise ValueError("List is empty") return sum(UpperCamelCase_) / len(UpperCamelCase_) if __name__ == "__main__": import doctest ...
17
"""simple docstring""" from __future__ import annotations from typing import Any class _lowerCAmelCase : """simple docstring""" def __init__( self : Any, UpperCAmelCase__ : int ): __lowercase = num_of_nodes __lowercase = [] __lo...
17
1
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCAmelCase_ : Optional[Any] = logging.getLogger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __...
362
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import (...
62
0
'''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_available from ......
58
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-bas...
58
1
import math def A_ ( _UpperCAmelCase , _UpperCAmelCase ): if ( not isinstance(_UpperCAmelCase , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("power_factor must be a valid float valu...
350
import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common impo...
127
0
"""simple docstring""" from __future__ import annotations import math import numpy as np from numpy.linalg import norm def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> float: return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(UpperCAmelCase , ...
69
"""simple docstring""" import sys from collections import defaultdict class UpperCamelCase : def __init__( self) -> Optional[int]: snake_case_ = [] def a_ ( self, lowerCAmelCase__) -> Any: return self.node_pos...
69
1
# 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...
185
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_t...
185
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_feat...
80
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import Toke...
80
1
from __future__ import annotations from typing import Any class lowercase : def __init__( self ,A__): lowercase = num_of_nodes lowercase = [] lowercase = {} def A__ ( self ,A__ ...
97
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ :Dict = { "configuration_luke": ["LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP", "LukeConfig"], "tokenization_luke": ["LukeTokenizer"], } try: if not is_torch_available(): ...
97
1
"""simple docstring""" import unittest from knapsack import greedy_knapsack as kp class snake_case__ ( unittest.TestCase ): def a__ ( self ): __a = [10, 20, 30, 40, 50, 60] __a = [2, 4, 6, 8, 10, 12] __a = 100 self.assertEqual(kp....
261
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name...
45
0
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ....
213
def UpperCAmelCase__ (UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ): """simple docstring""" snake_case = len(UpperCamelCase_ ) snake_case = [[0] * n for i in range(UpperCamelCase_ )] for i in range(UpperCamelCase_ ): ...
213
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward fro...
313
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, B...
325
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase =logging.get_logger(__name__) UpperCAmelCase ={ "microsoft/focalnet...
77
"""simple docstring""" from __future__ import annotations import math from collections.abc import Callable def _A ( _a : Callable[[int | float], int | float] , _a : int | float , _a : int | float , _a : int = 1_0_0 , ): """simple docs...
77
1
'''simple docstring''' from maths.prime_check import is_prime def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(__UpperCAmelCase, __UpperCAmelCase ): snake_case_ = F"Input value of [number={number}] must be an integer" ...
56
'''simple docstring''' import re from filelock import FileLock try: import nltk a : Union[str, Any] = True except (ImportError, ModuleNotFoundError): a : Any = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', q...
56
1
"""simple docstring""" def _lowercase ( UpperCamelCase_ , UpperCamelCase_ ) -> float: '''simple docstring''' _validate_point(UpperCamelCase_ ) _validate_point(UpperCamelCase_ ) if len(UpperCamelCase_ ) != len(UpperCamelCase_ ): raise ValueError('Both ...
366
import math def _lowercase ( UpperCamelCase_ , UpperCamelCase_ ) -> float: '''simple docstring''' if initial_intensity < 0: raise ValueError('The value of intensity cannot be negative' ) # handling of negative values of initial intensity if angle ...
169
0
'''simple docstring''' import unittest from transformers import 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_commo...
152
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require...
19
0
'''simple docstring''' from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class a__ ( a__ ): '''s...
228
'''simple docstring''' import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logge...
228
1
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None ...
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for a...
45
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""") def lowerCAmelCase_ ( ) ...
266
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl im...
266
1
"""simple docstring""" import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMi...
261
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnP...
261
1
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, TensorFlowBenchmarkArguments @require...
357
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def _UpperCAmelCase (UpperCamelCase_ : Tuple , UpperCamelCase_ : Dict ): '''simple docstring''' _lowerCAmelCase : ...
159
0
'''simple docstring''' _A : Any ={'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []} _A : Optional[Any] =['''a''', '''b''', '''c''', '''d''', '''e'''] def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperC...
41
lowerCamelCase : List[Any] =[ (1000, '''M'''), (900, '''CM'''), (500, '''D'''), (400, '''CD'''), (100, '''C'''), (90, '''XC'''), (50, '''L'''), (40, '''XL'''), (10, '''X'''), (9, '''IX'''), (5, '''V'''), (4, '''IV'''), (1, '''I'''),...
189
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device fro...
356
"""simple docstring""" import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to...
128
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.se...
26
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, ...
14
0
import requests def snake_case( __magic_name__ , __magic_name__ ) -> None: '''simple docstring''' lowercase : Tuple = {'''Content-Type''': '''application/json'''} lowercase : List[str] = requests.post(__magic_name__ , ...
116
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( 'The converte...
116
1
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp ...
31
# 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 appli...
330
0
"""simple docstring""" lowerCAmelCase : List[Any] = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def a__ ( ) -> None: lowerCamelCase = input("""Enter message: """ ) lowerCamelCase = input("""Enter key [alphanumeric]: """ ) lowerCamelCase ...
168
"""simple docstring""" import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, Rober...
168
1
"""simple docstring""" import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING f...
132
"""simple docstring""" 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 DEFAU...
132
1
"""simple docstring""" class SCREAMING_SNAKE_CASE_ : """simple docstring""" def __init__( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SC...
255
"""simple docstring""" import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=1024 ): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE...
255
1
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteS...
211
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __snake_case ( a , unittest.TestCase ): UpperCAmelCase__ : Any = PhobertTo...
51
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/LI...
234
"""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.pr...
234
1
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class lowercase( __a ): '''simple docstring''' lowercase__ = "" lo...
64
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import ded...
64
1
'''simple docstring''' from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) lowerCamelCase : Any = 2_9_9_7_9_2_4_5_8 # Symbols lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase : Tuple = symbols("ct x y z") def...
114
'''simple docstring''' # 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 # # Unl...
114
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenizatio...
280
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = ...
280
1
from __future__ import annotations import unittest from transformers import DistilBertConfig, 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_tensor, random_attention_ma...
138
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import...
138
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_lxmert''': ['''LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP''...
153
'''simple docstring''' import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, requir...
79
0
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from ...
366
'''simple docstring''' import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProc...
299
0
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class __lowerCAmelCase ( UpperCAmelCase__ ): snake_case_ : str = "EncodecFeatureExtractor" snake_case_ : int = ("T5Tokenizer", "T5Tok...
133
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate lowercase_ : Optional[Any] = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), data...
133
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channe...
368
import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase )...
257
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 ...
36
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compu...
193
0
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTe...
359
import math from collections.abc import Iterator from itertools import takewhile def UpperCAmelCase_( a__ ): """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 ...
19
0
'''simple docstring''' import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_...
53
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging a__ : Any ...
53
1
'''simple docstring''' import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""defa...
13
'''simple docstring''' import argparse import os import torch from transformers.utils import WEIGHTS_NAME __UpperCamelCase = ["small", "medium", "large"] __UpperCamelCase = "lm_head.decoder.weight" __UpperCamelCase = "lm_head.weight" def ...
13
1
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): ...
10
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __lowerCamelCase ( ): """simple docstring""" lowercase__ : Dict = ArgumentParser( description=( ...
130
0
import argparse import struct import unittest class __a: """simple docstring""" def __init__( self ,_SCREAMING_SNAKE_CASE ) -> None: UpperCAmelCase_ : Any = data # Initialize hash values UpperCAmelCase_ : List[Any] ...
235
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...tes...
235
1
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 10**-10 ) -> List[str]: _lowercase : Optional[Any] = a while ...
21
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBack...
64
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ : Optional[int] = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if no...
359
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES A_ : Union[str, Any] = logging.get_logger(__name__) A_ : int = OrderedDict( [ # Ba...
141
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase : List[Any] = { 'configuration_xlm': ['XLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMConfig', 'XLMOnnxConfig'], 'tokenization_xl...
27
'''simple docstring''' import requests from bsa import BeautifulSoup def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "https://www.worldometers.info/coronavirus" ): __a : List[Any] = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE ).text , 'html.parser' ...
27
1
def _UpperCAmelCase (UpperCamelCase_ : list[int] , UpperCamelCase_ : list[int] , UpperCamelCase_ : int ): '''simple docstring''' return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(UpperCamelCase__ ) ) def _U...
363
import os from datetime import datetime as dt from github import Github _lowerCamelCase : List[Any] = [ "good first issue", "good second issue", "good difficult issue", "enhancement", "new pipeline/model", "new scheduler", "wip", ] def _UpperCAmelCase (): ''...
159
0
from __future__ import annotations import math def SCREAMING_SNAKE_CASE_ ( __A : int ) -> list[int]: """simple docstring""" if num <= 0: a_ : str = F"""{num}: Invalid input, please enter a positive integer.""" rais...
32
'''simple docstring''' from __future__ import annotations from statistics import mean def a_ ( lowerCamelCase : list[int] , lowerCamelCase : list[int] , lowerCamelCase : int ): lowerCAmelCase = [0] * no_of_processes lowerCAmelCase = [0] * no_of_proces...
4
0
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transfor...
224
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import Inte...
224
1
"""simple docstring""" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : str ): '''simple docstring''' if num < 0: return False lowerCAmelCase = num lowerCAmelCase = 0 while num > 0: lowerCAmelCase ...
46
'''simple docstring''' import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from trans...
250
0
'''simple docstring''' def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' snake_case_ = [] snake_case_ = set({"(", "[", "{"} ) snake_case_ = set({")", "]", "}"} ) snake_case_ = {"{": "}", "[...
356
'''simple docstring''' from __future__ import annotations import numpy as np def UpperCamelCase_( snake_case : np.ndarray ): '''simple docstring''' snake_case_ , snake_case_ = np.shape(snake_case ) if rows != columns: snake_case_ ...
92
0
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import Stab...
207
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__ : Optional[int] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pas...
207
1
# Lint as: python3 import itertools import os import re _UpperCAmelCase : str = re.compile(R"""([A-Z]+)([A-Z][a-z])""") _UpperCAmelCase : Dict = re.compile(R"""([a-z\d])([A-Z])""") _UpperCAmelCase : Dict = re.compile(R"""(?<!_)_(?!_)""") _UpperCAmelCase : Tupl...
363
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase : Tuple = { """configuration_xlm_roberta_xl""": [ """XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMRobertaXLConfig""", """XLMRob...
200
0
'''simple docstring''' def A_ ( snake_case ): SCREAMING_SNAKE_CASE:Optional[Any] = generate_pascal_triangle(__A ) for row_idx in range(__A ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=" " ) # Print row...
139
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = ...
80
0
"""simple docstring""" import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import g...
272
"""simple docstring""" from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, ran...
272
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } ...
69
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : Any) -> Dict: '''simple docstring''' __UpperCamelCase : Op...
232
0
'''simple docstring''' from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class _a ( __lowerCAmelCase ): def __lt__( self ,_SCREAMING_SNAKE_CASE ) -> int: retu...
142
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class _a : SCREAMING_SNAKE_CASE_ : int SCREAMING_SNAKE_CASE_ : TreeNode | None = None SCREAMING_SNAKE_CASE_ : ...
142
1
'''simple docstring''' from __future__ import annotations from collections.abc import Callable A__ : List[Any] = list[list[float | int]] def UpperCAmelCase__ ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any ) -> int: __lowerCamelCase : int ...
185
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
287
0
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wav...
353
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ...
335
0
"""simple docstring""" UpperCAmelCase_ : str = """0.21.0""" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_l...
91
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] ...
91
1
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, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Enc...
122
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
122
1
"""simple docstring""" import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL SCREAMING_SNAKE_CASE__ = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def UpperCA...
46
'''simple docstring''' def __UpperCamelCase ( UpperCAmelCase ): lowercase__ : List[str] = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __UpperCamelCase ( UpperCAmelCase = 100 ): lowercase__ : Dict = 1 lowercase__ : Optional[in...
198
0
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 ...
347
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Optional[Any] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config"...
347
1
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testin...
203
"""simple docstring""" def __lowerCAmelCase ( lowercase : list ) -> int: """simple docstring""" 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][c...
203
1
from math import factorial lowerCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def __lowerCamelCase ( lowerCAmelCase__ ): if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError('Parameter number must be int' ) ...
356
from __future__ import annotations lowerCAmelCase__ = tuple[int, int, int] lowerCAmelCase__ = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase lowerCAmelCase__ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # -------------------------- default selecti...
119
0
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Un...
296
def __lowercase ( _SCREAMING_SNAKE_CASE = 10 ) -> str: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or n < 0: raise ValueError("""Invalid input""" ) SCREAMING_SNAKE_CASE = 10**n SCREAMING_SNAK...
296
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch i...
323
__A : Dict = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] __A : List[Any] = [ ...
323
1
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder __UpperCAmelCase = datasets.utils.logging.get_logger(__name__) class lowerCamelCase (folder_based_builder.FolderBasedBuilderC...
29
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str ...
267
0
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB 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...
175
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class __snake_case ( _lowercase , ...
175
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCamelCase : Optional[int] = { 'configuration_altclip': [ 'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AltCLI...
77
'''simple docstring''' from __future__ import annotations def a__ ( lowercase : str, lowercase : list[str] | None = None, lowercase : dict[str, float] | None = None, lowercase : bool = False, ) -> tuple[int, float, str]: """simple docs...
324
0
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig 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 ...te...
357
from random import randint from tempfile import TemporaryFile import numpy as np def __snake_case ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : str , _lowerCAmelCase : Optional[int] ) -> Dict: A_ : Optional[Any] = 0 if start < end: A_ : Tuple = ...
70
0
"""simple docstring""" def lowercase ( _snake_case : int , _snake_case : int ) ->str: """simple docstring""" if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __snake_case : Tuple = str(bin(_snake_case ) ...
102
import baseaa def lowerCamelCase_ ( UpperCamelCase__ : str ) -> bytes: """simple docstring""" return baseaa.aaaencode(string.encode('utf-8' ) ) def lowerCamelCase_ ( UpperCamelCase__ : bytes ...
90
0
import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, t...
353
from ..utils import DummyObject, requires_backends class a_ ( metaclass=_snake_case ): UpperCamelCase__ : Any =["torch", "scipy"] def __init__( self :List[str] , *_lowercase :List[str] , **_lowercase :Union[str, Any]) -> List[Any]: ...
344
0
"""simple docstring""" import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def A_ ( _lowercase ): '''simple docstring''' return sum(param.float().s...
66
from __future__ import annotations def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = len(SCREAMING_SNAKE_CASE__ ) # We need to create solution object to save path. snake_case_ = [[0 for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAM...
8
0
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class __a ( __UpperCamelCase ): def __init__( self : Union[str, Any] , *UpperCAmelCase : Optio...
356
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __U...
28
0
'''simple docstring''' import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() __a = logging.get_logger("transformers.models.speecht5") def __snake_case( _lowerCAmelCase , _lowerCAmel...
35
'''simple docstring''' import argparse import os import re import packaging.version UpperCamelCase__: Union[str, Any] = "examples/" UpperCamelCase__: Optional[Any] = { "examples": (re.compile(r"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_ve...
23
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBloc...
361
'''simple docstring''' import os import numpy import onnx def _a ( _lowerCamelCase , _lowerCamelCase ) -> Any: """simple docstring""" __snake_case : Optional[int] = a.name __snake_case : Dict = ...
13
0
import random from .binary_exp_mod import bin_exp_mod def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=1000 ): '''simple docstring''' if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd lowercase = n - 1 ...
101
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class __magic_name__ : def __init__( self : str , lowercase_ : Dict ): if isinst...
239
0
def __lowerCamelCase ( lowerCAmelCase__ = 1_0_0_0 ): return sum(e for e in range(3 , lowerCAmelCase__ ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(F'{solution() = }')
361
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitF...
119
0
"""simple docstring""" 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, )...
102
"""simple docstring""" from __future__ import annotations from scipy.special import comb # type: ignore class _UpperCAmelCase : '''simple docstring''' def __init__(self , a_ ): '''simple docstring''' __snake_case : List[str] = list_of_points # Degree determ...
102
1
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) de...
367
"""simple docstring""" import numpy as np from PIL import Image def snake_case__ ( __lowerCamelCase : np.ndarray , __lowerCamelCase : int , __lowerCamelCase : int ): """simple docstring""" lowerCamelCase__ : List[Any] =np.array(__lowerCamelCase ...
272
0