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 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 ......
340
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.pat...
314
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, ...
370
"""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
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { 'configuration_clipseg': [ 'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPSegConfig', 'CLIPSegTextConfig', ...
341
'''simple docstring''' from __future__ import annotations def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ): if len(_SCREAMING_SNAKE_CASE ) == 0: return [] _snake_case, _snake_case = min(_SCREAMING_SNAKE_CASE ), max(_SCREAMING_SNAKE_CASE ) ...
341
1
import re from filelock import FileLock try: import nltk _lowerCamelCase = True except (ImportError, ModuleNotFoundError): _lowerCamelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def SCREAM...
351
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Dict=2_8123 ) -> str: UpperCAmelCase_ = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum...
177
0
def UpperCamelCase ( __magic_name__ : float , __magic_name__ : float ) -> float: """simple docstring""" return price * (1 + tax_rate) if __name__ == "__main__": print(F'{price_plus_tax(1_0_0, 0.25) = }') print(F'{price_plus_tax(125.50, 0.05) = }')
305
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 requi...
0
0
def lowercase__ ( __snake_case : str , __snake_case : str ): '''simple docstring''' def get_matched_characters(__snake_case : str , __snake_case : str ) -> str: UpperCAmelCase_ : List[Any] = [] ...
357
def lowercase__ ( __snake_case : Tuple , __snake_case : List[Any] ): '''simple docstring''' UpperCAmelCase_ : Any = '' for i in table: res += inp[i - 1] return res def lowercase__ ( __snake_case...
145
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolv...
153
"""simple docstring""" class _UpperCAmelCase : def __init__( self :List[str] , __UpperCamelCase :Union[str, Any] , __UpperCamelCase :Tuple ): A = name A = val def __str__( self :str ): return f"{self.__class__.__nam...
292
0
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, EulerAncestralDiscreteScheduler, EulerDiscreteSche...
110
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from .....
110
1
'''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__) class lowerCAmelCase_ ( lowerCamelCa...
346
'''simple docstring''' from math import factorial def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int = 20 ): '''simple docstring''' UpperCAmelCase__ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCAmelCase__ = n // 2...
346
1
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Any =argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str...
106
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorForm...
106
1
"""simple docstring""" a : Tuple = ''' # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git ''' a : Optional[int] = [{'''type''': '''code''', '''c...
105
from torch import nn class a ( nn.Module ): def __init__( self :Tuple ,__lowercase :Optional[int] ,__lowercase :int ): super().__init__() snake_case__ : Optional[Any] = class_size snake_case__ : Dict = embed_size ...
230
0
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters lowerCAmelCase__ : List[Any] =(720, 1280) # Height, Width lowerCAmelCase__ : Union[str, Any] =(0.4, 0.6) # if height or width lower than thi...
359
from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Optional[int] = ['''speech'''] def __init__( self , *_A , **_A ): '''sim...
118
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A_ : Tuple = { """configuration_transfo_xl""": ["""TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TransfoXLConfig"""], """tokeni...
215
'''simple docstring''' from numpy import exp, pi, sqrt def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ = 0.0 , lowerCAmelCase_ = 1.0 )-> int: '''simple docstring''' return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if _...
215
1
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCamelCase__ ( __lowerCamelCase : ndarray ): return np.dot(__lowerCamelCase , __lowerCamelCase ) class __magic_name__ : ...
361
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase ={ 'configuration_groupvit': [ 'GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GroupViTConfig', 'GroupViTOnnxCo...
242
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase : str = logging.get_logger(__name__) _...
88
import re import string import numpy as np import datasets __lowerCAmelCase : Optional[int] = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' __lowerCAmelCase : Optional...
88
1
class _a : def __init__(self ) -> str: UpperCAmelCase_: Dict = 0 UpperCAmelCase_: Any = 0 UpperCAmelCase_: List[Any] = {} def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> str: if vertex not...
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''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, ...
80
'''simple docstring''' from __future__ import annotations lowerCamelCase__ = 'Muhammad Umer Farooq' lowerCamelCase__ = 'MIT' lowerCamelCase__ = '1.0.0' lowerCamelCase__ = 'Muhammad Umer Farooq' lowerCamelCase__ = 'contact@muhammadumerfarooq.me' lowerCamelCase__ = '...
234
0
from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __A : Optional[Any] = logging.get_logger(__name__) class ...
49
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to hav...
49
1
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_avail...
231
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer __A = logging.get_logger(__name__) __A ...
177
0
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_ut...
363
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler...
192
0
import os import pytest from transformers.dynamic_module_utils import get_imports SCREAMING_SNAKE_CASE__ : str = '\nimport os\n' SCREAMING_SNAKE_CASE__ : str = '\ndef foo():\n import os\n return False\n' SCREAMING_SNAKE_CASE__ : Any = '\ndef foo...
48
'''simple docstring''' from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def __UpperCAmelCase ( a_: str = "isbn/0140328726" ): _UpperCAmelCase : Dict = olid.strip().strip("/" ) # Remove leading/trailing whitespac...
145
0
import math def lowerCamelCase_ ( UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. re...
348
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 ...
348
1
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _a ( UpperCamelCase__ , unittest.TestCase ): _lowercase : Tuple = CTRL...
110
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, ...
110
1
"""simple docstring""" import os _a = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 1_00, """D""": 5_00, """M""": 10_00} def _A ( UpperCamelCase_ : Optional[int]) -> Optional[Any]: '''simple docstring''' __lowercase = 0 __lowercase = ...
353
"""simple docstring""" from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAv...
144
0
"""simple docstring""" import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline __UpperCamelCase : Optional[int] = { '''n_samples''': 6_4, '''horizon''': 3_2, '''num_inference_steps''': 2_0, '''n_guide_steps''': 2, # can set to 0 fo...
106
"""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 __UpperCamelCase : Optional[Any] = '''scheduler_conf...
106
1
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : '''simple docstring''' lowerCamelCase_ :torch.Tensor # [batch_size x 3] lowerCamelCase_ :torch.Tensor # [batch_size x 3] ...
355
'''simple docstring''' from manim import * class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Dict = Rectangle(height=0.5 , width=0.5 ...
274
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=...
124
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class lowerCamelCase (SCREAMING_SNAKE_CASE__ ,...
118
0
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __lowerCAmelCase (*__lowerCAmelCase ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): _UpperCAmelCase : Any = ...
322
'''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
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : List[Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ...
93
"""simple docstring""" import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transf...
242
0
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE (UpperCAmelCase ): pass class SCREAMING_SNAKE_CASE : def __init__( self : List[str] , a : Any )-> None: """simple docstrin...
269
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class SCREAMING_SNAKE_CASE (UpperCAmelCase ): def __init__( self : List[str] , a : Call...
269
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, ...
208
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
from abc import ABC, abstractmethod from argparse import ArgumentParser class __UpperCAmelCase ( _lowerCamelCase ): @staticmethod @abstractmethod def lowerCamelCase ( lowerCAmelCase_ ): """simple docstring""" raise NotImplementedError() ...
353
'''simple docstring''' from __future__ import annotations from collections import namedtuple def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> tuple: _snake_case = namedtuple('result' , 'name value' ) if (voltage, current, power).count(0 ...
160
0
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin...
49
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case :Union[str, Any] = logging.get_logger(__name__) __snake_case :Any = { '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''', } class ...
49
1
"""simple docstring""" import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) UpperCAmelCase = logging.getLogger() ...
366
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase = logging.get_logger(__name__) # TODO: upload to AWS UpperCAmelCase = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-...
172
0
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 _lowercase ( A__ ): '''s...
9
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline A_ : List[str] = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std...
192
0
def _a ( SCREAMING_SNAKE_CASE__ : int ) -> bool: '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = f'''Input value of [number={numb...
191
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": _lowerCamelCase : Union[str, Any] = '''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(i...
191
1
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Optional[Any]: """simple docstring""" global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: A__ = mf_knapsack(...
14
'''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 __lowercase ( tf.keras.layers.Layer ): def __init__(self , ...
318
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_sp...
364
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 Stabl...
293
0
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate __SCREAMING_SNAKE_CASE :Optional[int] = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, ...
22
"""simple docstring""" import re from filelock import FileLock try: import nltk A__ : Any = True except (ImportError, ModuleNotFoundError): A__ : str = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', q...
144
0
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common i...
356
'''simple docstring''' import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { '''post_extrac...
299
0
"""simple docstring""" import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class ...
105
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging A : Dict = logging.get_logger(__name__) def __lowerCamelCase ( __a :int=None , __a ...
274
0
"""simple docstring""" import baseaa def snake_case__ ( __lowerCamelCase : str ): """simple docstring""" return baseaa.baaencode(string.encode('''utf-8''' ) ) def snake_case__ ( __lowerCamelCase : bytes ): """simple docstring""" return ...
355
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device _lowercase : Tuple = False class __SCREAMING_SNAKE_CASE ...
272
0
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _a ( *SCREAMING_SNAKE_CASE : str ) -> Dict: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _...
322
import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def _a ( SCREAMING_SNAKE_CASE : Optional[int] ) -> Union[str, Any]: """simple docstring...
322
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A : Any = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfi...
359
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A : Optional[Any] = logging.get_logger(__name__) A : Tuple = { 'YituTech/conv-bert-base': 'https://h...
146
0
"""simple docstring""" def _lowercase ( __snake_case ,__snake_case ) -> int: return int((input_a, input_a).count(1 ) != 0 ) def _lowercase ( ) -> None: assert or_gate(0 ,0 ) == 0 assert or_gate(0 ,1 ) == 1 assert or_gate(1 ,0 ) == 1 ...
269
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot f...
269
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __SCREAMING_SNAKE_CASE : List[Any] = { '''configuration_layoutlmv2''': ['''LAYOU...
370
"""simple docstring""" import os import sys __SCREAMING_SNAKE_CASE : Dict = os.path.join(os.path.dirname(__file__), '''src''') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering,...
73
0
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is...
300
"""simple docstring""" A = 9.80665 def __A ( a_ :float , a_ :float , a_ :float = g) -> float: if fluid_density <= 0: raise ValueError('''Impossible fluid density''') if volume < 0: raise ValueError('''Impossible Obj...
160
0
from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader ...
370
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils impo...
115
0
from __future__ import annotations from collections import namedtuple def lowercase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ) -> tuple: _snake_case : int = namedtuple("""result""" , """name ...
317
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : Union[str, Any]= logging.get_logger(__name__) _a : str= { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json", }...
172
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a = { 'configuration_blip_2': [ 'BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Blip2Config', 'Blip2QFormerConfig', 'Blip2VisionC...
361
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
144
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = { "configuration_blip_2": [ "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Blip2Config", "Blip2QFormerConf...
191
"""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 lowerCamelCase_ = logging.get_logger(__name__) lowerCa...
191
1
import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_COMMIT...
26
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger("transformers.models.speecht5") def _a ( a :Optional[Any] , a :Tuple...
26
1
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIF...
10
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): ...
293
0
from __future__ import annotations def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = [] while i * i <= n: if n % i: i += 1 else: n //= i factors....
218
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def UpperCAmelCase_ ( _A , _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = args.log...
218
1
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 snake_case_ : Optional[Any] = False class __snake_ca...
51
from __future__ import annotations from collections.abc import Callable __UpperCAmelCase = list[list[float | int]] def A__ ( __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = len(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = [[0 for _ in range(size + 1 )] for _ in ...
299
0
"""simple docstring""" def _snake_case ( lowercase__ : float , lowercase__ : float , lowercase__ : int ) -> float: '''simple docstring''' if principal <= 0: raise Exception("""Principal borrowed must be > 0""" ) if rate_per_annum < 0: ...
1
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_s...
1
1
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 10**-10 )-> float: '''simple docstring''' UpperCAmelCase :...
348
'''simple docstring''' def snake_case__ ( _A: str ) -> list[int]: '''simple docstring''' lowerCAmelCase = [0 for i in range(len(_A ) )] # initialize interval's left pointer and right pointer lowerCAmelCase , lowerCAmelCase = 0, 0 for i in range(1 , le...
272
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 lowercase (_A ): """simple d...
25
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase : Optional[Any] = { """CarlCochet/trajectory-transformer-halfcheetah-m...
25
1
def a ( A__ : int ) -> Union[str, Any]: """simple docstring""" if a < 0: raise ValueError('Input value must be a positive integer' ) elif isinstance(A__ , A__ ): raise TypeError('Input value must be a \'int\' typ...
205
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _a ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any ...
146
0
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionM...
12
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...
12
1
"""simple docstring""" def lowercase ( A_ )-> bool: '''simple docstring''' return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
40
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) _...
73
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ...
265
def _a ( UpperCAmelCase ) -> bool: """simple docstring""" return str(UpperCAmelCase ) == str(UpperCAmelCase )[::-1] def _a ( UpperCAmelCase ) -> int: """simple docstring""" return int(UpperCAmelCase ) + int(str(UpperCAmelCase )[::-1]...
265
1
'''simple docstring''' lowercase__ = { "joule": 1.0, "kilojoule": 1000, "megajoule": 1000000, "gigajoule": 1000000000, "wattsecond": 1.0, "watthour": 3600, "kilowatthour": 3600000, "newtonmeter": 1.0, "calorie_nutr": 4186.8, "kilocalorie_nutr": 4186800.00...
151
"""simple docstring""" import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset UpperCAmelCase : str = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4:...
115
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule _snake_case = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _snake_case ...
363
"""simple docstring""" from math import factorial def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if successes > trials: raise ValueError("""successes must be lower or equal to trials"...
324
0
import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_checkpoint_call...
8
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : int = logging.get_logger(__name__) A__ : List[str] = { 'google/pix2struct-textcaps-base': ( 'https://...
144
0
import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline _lowerCAmelCase : List[str] = version.par...
308
import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMix...
308
1
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, ...
26
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.ro...
26
1
"""simple docstring""" import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_mode...
357
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 import CORPUS...
225
0
import math import flax.linen as nn import jax.numpy as jnp def UpperCamelCase_( _snake_case : jnp.ndarray , _snake_case : int , _snake_case : float = 1 , _snake_case : float = 1 , _snake_case : float = 1.0e4 , _snake_cas...
218
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCAmelCase : List[str] = logging.get_logger(__na...
218
1
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_ut...
1
"""simple docstring""" def _snake_case ( lowercase__ : list , lowercase__ : list , lowercase__ : int , lowercase__ : int , lowercase__ : int ) -> int: '''simple docstring''' if index == number_of_items: return 0 lowerCA...
1
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : float , snake_case_ : float , snake_case_ : int ) -> float: '''simple docstring''' if principal <= 0: raise Exception("Principal borrowed must be > 0" ) if rate_per_annum < ...
1
'''simple docstring''' from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelera...
1
1
'''simple docstring''' import collections import importlib.util import os import re from pathlib import Path lowerCAmelCase : int ='src/transformers' # Matches is_xxx_available() lowerCAmelCase : Any =re.compile(r'''is\_([a-z_]*)_available()''') # Catches a one-lin...
368
'''simple docstring''' def UpperCAmelCase_ ( __lowerCamelCase : str ,__lowerCamelCase : str ): lowercase_ :Optional[Any] = len(__lowerCamelCase ) lowercase_ :List[Any] = [] for i in range(len(__lowerCamelCase ) - pat_len + 1 ): l...
147
0
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class lowerCAmelCase_ (a__ ): """simple docstring""" def __init__(self , SCREAMING...
25
"""simple docstring""" import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : List[str...
25
1
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import...
368
from __future__ import annotations def lowerCamelCase_ ( lowerCAmelCase: list , lowerCAmelCase: int | None = None , lowerCAmelCase: int | None = None )-> None: if start is None: _snake_case : int = 0 if end is None: _snake_case : Option...
260
0
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_saf...
12
from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...util...
12
1
def __UpperCamelCase ( UpperCAmelCase = 6008_5147_5143 ): try: lowercase__ : Tuple = int(__A ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one....
357
'''simple docstring''' import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class UpperCAmelCase ( tf.keras.optimizers.schedules.LearningRateSc...
214
0
'''simple docstring''' import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def __lowerCamelCase ( _lowercase , _lowercase ) -> Optional[int]: UpperC...
265
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a : Optional[int] = { """configuration_git""": ["""GIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GitConfig""", """GitVisionConfig"""], """processing_git...
265
1
def UpperCamelCase ( __lowerCamelCase : List[Any] ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(__lowerCAmelCase ) == 0: raise ValueError("Input list m...
371
import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = """▁""" __lowerCamelCase ...
10
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torc...
336
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ : Tuple = { 'configuration_mctct': ['MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MCTCTConfig'], 'feature_extraction_mctct': ['MCTCTFeatur...
324
0
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_text import VOCAB_FILES_NAMES, save_json from tr...
370
import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__=False ): lowerCamelCase_ = OmegaConf.load(lowerCamelCase__ ) if display: print(yaml.dump(Omega...
47
0
import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline lowerCAmelCase_ = version.parse(version.par...
308
import os def snake_case( __magic_name__ = "input.txt" ) -> int: '''simple docstring''' with open(os.path.join(os.path.dirname(__magic_name__ ) , __magic_name__ ) ) as input_file: lowercase : Any = [ [int(...
308
1
'''simple docstring''' import math def UpperCamelCase_ ( A__ : int ): '''simple docstring''' lowerCAmelCase_ : int = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(A__ ) def ...
89
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_avail...
89
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor a_ : List[str] = logging.get_logger(__name__) class snake_case ( _SCREAMING_SNAKE_CASE ): """simple docstring""" ...
55
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def UpperCAmelCase_ ( __UpperCAmelCase : bytes , __UpperCAmelCase : int ) -> np.array: SCREAMING_SNAKE_CASE_ = f"{sampling_rate}" SCREAMING_SN...
225
0
'''simple docstring''' from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar _SCREAMING_SNAKE_CASE : Tuple = TypeVar("T") def UpperCamelCase_( snake_case : int ): '''simple docstring''' return (position - 1...
92
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[int] = { "edbeeching/decision-transformer-gym-hopper-medium": (...
92
1
'''simple docstring''' import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFe...
1
'''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_ten...
1
1
"""simple docstring""" from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _UpperCAmelCase ( _a ): a__ : str = CustomTokenizer pass
368
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowercase : List[Any] = { 'configuration_mvp': ['MVP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MvpConfig', 'MvpOnnxConfig'], ...
86
0
def UpperCamelCase( __UpperCamelCase : str ): return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(__UpperCamelCase ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__('''doctest''').testmod()
103
from torch import nn def lowerCAmelCase_ (lowerCAmelCase__: Optional[int] ): """simple docstring""" if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() ...
147
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER,...
25
'''simple docstring''' from __future__ import annotations from typing import Any def lowercase (_A ): """simple docstring""" if not postfix_notation: return 0 _lowerCAmelCase : int = ...
25
1
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTe...
49
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : Optional[Any] = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-...
260
0
"""simple docstring""" import baseaa def A ( snake_case :str ) -> bytes: return baseaa.aaaencode(string.encode('utf-8' ) ) def A ( snake_case :bytes ) -> str: return baseaa.aaadecode(snake_case ).decode('utf-8' ) if __name__ == "__main__": ...
263
"""simple docstring""" import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncodin...
263
1
'''simple docstring''' lowerCamelCase : List[str] = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': ...
2
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging snake_case_ = logging.get_logger(__name__) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : ...
214
0
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to hav...
370
from __future__ import annotations import math def lowerCAmelCase_ ( _lowercase : int) -> list[int]: """simple docstring""" if num <= 0: a__ : Tuple = F'''{num}: Invalid input, please enter a positive integer.''' raise ValueE...
266
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandin...
44
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = (DDPMParallelScheduler,) def SCREAMING_SNAKE_CASE_ (self : Any ,...
10
0
'''simple docstring''' def snake_case__ ( lowerCamelCase__ : list ) -> list: if len(UpperCamelCase__ ) < 2: return collection def circle_sort_util(lowerCamelCase__ : list , lowerCamelCase__ : int , lowerCamelCase__ : ...
366
'''simple docstring''' import pprint import requests snake_case__ = """https://zenquotes.io/api""" def snake_case__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def snake_case__ ( ) -> list: return ...
4
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : str = logging.get_logger(__name__) _lowerCAmelCase : List[Any] = { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/config.json", # See all XGLM...
169
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : int = {"configuration_glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"]} try: if not is_vision_available()...
47
0
'''simple docstring''' import inspect import unittest from math import floor from transformers import CvtConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configurati...
358
'''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
0
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: if nth_term == "": return [""] _a : Optional[int] = int(lowerCAmelCase_ ) _a : int = int(lowerCAm...
89
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import ...
89
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir...
353
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...
261
0
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel UpperCamelCase__ = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attention.self""", """s...
92
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 def _a ( SCREAMING_SNAKE_CASE_ ...
92
1
'''simple docstring''' import random class _UpperCamelCase : '''simple docstring''' @staticmethod def __lowerCamelCase ( _lowerCAmelCase : str): '''simple docstring''' __lowercase =[ord(_lowerCAmelCase) for i in text] ...
48
'''simple docstring''' import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging lowerCamelCase ...
48
1