code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class A__ ( _lowerCAmelCase , unittest.TestCase...
276
"""simple docstring""" from math import factorial class lowerCamelCase : '''simple docstring''' def __init__( self: Optional[int] , snake_case: Dict , snake_case: int ) -> Tuple: snake_case_ :List[Any] = real if ...
66
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast f...
369
import comet # From: unbabel-comet import torch import datasets snake_case_ : Tuple = datasets.logging.get_logger(__name__) snake_case_ : str = "\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n tit...
7
0
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, id...
290
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling ...
336
0
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, ...
343
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = ...
343
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config...
113
"""simple docstring""" # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowercase (SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int ) -> List[str]: SCREAMING_SNAKE_CASE ...
113
1
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_speech_available(): from tran...
359
from string import ascii_uppercase A : Optional[int] = {char: i for i, char in enumerate(ascii_uppercase)} A : Union[str, Any] = dict(enumerate(ascii_uppercase)) def __lowerCAmelCase ( a__ , a__ ) -> str: __a = len(a__ ) __a ...
33
0
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black _UpperCamelCase : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies ...
220
'''simple docstring''' def UpperCAmelCase_ ( __lowercase : str ) -> list: '''simple docstring''' if n_term == "": return [] _UpperCAmelCase = [] for temp in range(int(__lowercase ) ): series.append(f'1/{te...
22
0
'''simple docstring''' def a__ ( lowercase : int ) -> int: """simple docstring""" if not isinstance(lowercase, lowercase ): raise TypeError('''Input value must be an \'int\' type''' ) _UpperCamelCase = 0 while number: ...
352
'''simple docstring''' def a__ ( lowercase : int, lowercase : int, lowercase : list[list[int]] ) -> int: """simple docstring""" def update_area_of_max_square(lowercase : int, lowercase : int ) -> int: # BASE CASE if row >= rows or col >= cols...
287
0
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class __snake_case ( a ): def lowerCamelCase ( self : Tuple): """simple docstring""" return [ {"col_1": 3...
51
import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import loggi...
119
0
import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __UpperCAmelCase : def __init__( self : Union[str, Any], __A : List[...
361
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets _lowerCamelCase : int = datasets.logging.get_logger(__name__) _lowerCamelCase : Any = "\\n@InProceedings...
99
0
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 import FlaxTimestepEmbedding, Fl...
116
def lowerCamelCase_ ( _a ): """simple docstring""" lowerCAmelCase__ : Optional[Any] = '''''' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def lowerCamelC...
131
0
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMSch...
197
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ : Dict = {"""configuration_swin""": ["""SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SwinConfig""", """SwinOnnxConfig"""]} try: if not is_torch_ava...
197
1
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class ...
55
"""simple docstring""" from math import pow def _UpperCAmelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , ) -> tuple[int, int]: if current_sum =...
288
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) ...
330
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = '''''' for i in table: res += inp[i - 1] return res def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" ...
330
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( sel...
45
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class l...
176
0
"""simple docstring""" 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 ( ...
366
"""simple docstring""" def __lowercase ( snake_case_ : int ) ->Optional[Any]: '''simple docstring''' stooge(snake_case_ ,0 ,len(snake_case_ ) - 1 ) return arr def __lowercase ( snake_case_ : Optional[Any] ,snake_case_ : Un...
291
0
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, loggi...
187
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import Confi...
7
0
"""simple docstring""" def _UpperCAmelCase ( __lowerCamelCase : int , __lowerCamelCase : int ) -> int: _snake_case = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): _snake_case = n - k # Calculate C(n,k) for i in range(__lower...
360
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils imp...
40
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a_ : Optional[Any] = logging.get_logger(__name__) a_ : List[str] = { """sh...
55
"""simple docstring""" from math import pow def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,): """simple docstring""" if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solution...
289
0
'''simple docstring''' from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import...
367
'''simple docstring''' def lowerCamelCase ( lowerCAmelCase : int ): """simple docstring""" if not isinstance(lowerCAmelCase , lowerCAmelCase ): __magic_name__ : int = f'Input value of [number={number}] must be an integer' raise TypeError(lowerCAmelCase ) if nu...
275
0
'''simple docstring''' from sklearn.metrics import matthews_corrcoef import datasets __snake_case = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It take...
97
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) ...
33
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: if not grid or not grid[0]: raise TypeError("""The grid does not contain the appropriate information""" ) for cell_n in range(1 , len(grid[0] ) ): ...
357
'''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_imag...
129
0
'''simple docstring''' __a: Dict = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def __UpperCamelCase ...
198
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_E...
287
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase: List[str] = logging.get_logger(__name__) _lowercase: Union[str, Any] = { "andreasmadsen/efficient...
71
def a( A : int , A : float , A : float ) -> float: """simple docstring""" return round(float(moles / volume ) * nfactor ) def a( A : float , A : float , A : float ) -> float: """simple docstring""" return round(float((moles * 0.0_...
71
1
'''simple docstring''' import math from datetime import datetime, timedelta def a ( __a ) -> datetime: '''simple docstring''' UpperCamelCase__ :Tuple = year % 19 UpperCamelCase__ :Optional[Any] = year % 4 UpperCamelCase__ :Dict = year...
97
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() lowercase : Any = logging.get_logger(__name__) def A_ ( A__ ) -> List[str]: a__ : Union[str, Any] = ...
99
0
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...
216
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) snake_case_ = { '''post_extract_proj''': '''feature_projection.projection'...
216
1
"""simple docstring""" import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class _A ( lowerCAmelCase , ...
197
"""simple docstring""" from ..utils import DummyObject, requires_backends class _A ( metaclass=lowerCAmelCase ): snake_case__ : str = ['torch', 'transformers', 'onnx'] def __init__( self , *__lowerCAmelCase , **__lowerCAmelCase ): ...
197
1
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class snake_...
186
"""simple docstring""" from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatu...
186
1
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def a__ ( _UpperCamelCase : list ,_UpperCamelCase : list ,_UpperCamelCase : list ,_UpperCamelCase...
330
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_para...
330
1
"""simple docstring""" from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig _lowerCAmelCase : List[Any] = logging.get_logger(__name__) _lowerCAmelCase : Union[str, Any] =...
298
"""simple docstring""" import unittest import numpy as np import requests 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_inp...
298
1
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor a__ = logging.get_logger(__name__) class snake_case ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Dict , *...
317
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging lowerCAmelCase : Tuple = logging.get_logger(__name__) ...
291
0
"""simple docstring""" import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_...
188
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) ...
188
1
"""simple docstring""" import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case__ : Any = logging.get_logger(__name__) snake_case__ : Dict = { '''facebook/encodec_24khz''': '''https://huggi...
60
"""simple docstring""" def lowercase ( A_ )-> str: '''simple docstring''' if isinstance(A_ , A_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(A_ , A_ ): raise TypeError("'str' obj...
40
0
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins UpperCAmelCase = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def _snake_case ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : i...
187
'''simple docstring''' class __snake_case: '''simple docstring''' def __init__( self ) -> None: lowerCAmelCase = {} # Mapping from char to TrieNode lowerCAmelCase = False def __snake_case ( self , A_ ) -> None: ...
187
1
def A (__A : str , __A : str ) -> float: """simple docstring""" def get_matched_characters(__A : str , __A : str ) -> str: UpperCAmelCase_ = [] UpperCAmelCase_ = min(len(_...
51
def _lowercase ( lowercase__ , lowercase__ ): if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCAmelCase : int = str(bin(lowercase__ ) )[2:] # remove the leading "0b" __lowerCAmelCase : Any...
275
0
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 import FlaxTimestepEmb...
356
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_...
125
0
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy 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 from ..models....
213
# 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/licenses/LICENSE-2.0 # # Unl...
129
0
"""simple docstring""" import numpy as np def SCREAMING_SNAKE_CASE_ ( snake_case : np.ndarray )-> np.ndarray: return 1 / (1 + np.exp(-vector )) def SCREAMING_SNAKE_CASE_ ( snake_case : np.ndarray )-> np.ndarray: return vector * sigmoid(snake_case ) if __na...
80
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): fro...
80
1
def A ( a_ ,a_ ) -> bool: __UpperCamelCase : str =len(a_ ) __UpperCamelCase : Any =len(a_ ) __UpperCamelCase : Union[str, Any] =[[False for _ in range(m + 1 )] for _ in range(n + 1 )] ...
71
from torch import nn class __A ( nn.Module ): """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" super().__init__() __UpperCamelCase : ...
71
1
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_...
39
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device a__: Union[str, Any] = False class SCREAMING_SNAKE_CASE_...
39
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase__ ={ 'configuration_rembert': ['REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RemBer...
216
def __UpperCamelCase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): __a : str = len(lowerCAmelCase__ ) __a : Optional[int] = [] for i in range(len(lowerCAmelCase__ ) - pat_len + 1 ): __a : str = True for j in range(lowerCAmelCase__ ): if s[i + j]...
216
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE...
365
def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' if index == number_of_items: return 0 SCR...
193
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UN...
186
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCamelCase = { """configuration_mobilevit""": ["""MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileViTConfig""", "...
186
1
from __future__ import annotations __SCREAMING_SNAKE_CASE : Optional[int] = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class lowercase_ : def __init__( self , ...
354
# 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 applicabl...
284
0
'''simple docstring''' import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore _lowerCAmelCase = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" _lowerCAm...
298
'''simple docstring''' import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers....
298
1
"""simple docstring""" import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoToke...
352
"""simple docstring""" def lowerCAmelCase_( lowercase_ : List[str] ) -> Optional[Any]: _lowerCamelCase = len(lowercase_ ) while cur > 1: # Find the maximum number in arr _lowerCamelCase = arr.index(max(arr[0:cur] ) ) # Reve...
73
0
def UpperCAmelCase__ ( _A : int ): '''simple docstring''' if num < 0: return False a__ =num a__ =0 while num > 0: a__ =rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod(...
188
from ..utils import DummyObject, requires_backends class __magic_name__ ( metaclass=lowerCamelCase__ ): '''simple docstring''' lowerCamelCase__ : List[Any] = ['torch'] def __init__( self, *lowercase_, **lowercase_ ) -> List[str]: """s...
188
1
"""simple docstring""" import numpy as np def a__ ( SCREAMING_SNAKE_CASE : np.ndarray ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def a__ ( SCREAMING_SNAKE_CASE : np.ndarray ): '''simple docstring''' return vector * sigmoid(SCREAMING...
353
"""simple docstring""" import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: ...
133
0
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 lowerCamelCase__ ( _A ): '''simple docstring''' snake_case_ ...
187
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCamelCase__ ( _A , _A=None ): '''simple docstring''' snake_case_ = None if token is n...
187
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase_ =logging.get_logger(__name__) Uppe...
350
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def a_ ( _lowercase ): # This defines a "chinese character" as anything in the CJK Unicode bl...
128
0
"""simple docstring""" import inspect import unittest from transformers import MobileViTConfig 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_c...
25
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case_ : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix...
125
0
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .t...
369
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow _a = logging.getLogger() @unittest.skip("""Temporarily disable the doc test...
23
0
'''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_mobilebert import MobileBertTokenizer a__ : List[str] = logging.ge...
80
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # In...
80
1
"""simple docstring""" from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, ...
363
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class lowe...
132
0
import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import Flax...
39
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transfor...
39
1
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler') class lowerCAmelCase__: ...
325
from __future__ import annotations import math def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(__lowerCamelCase ) == 0: ...
325
1
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( lowercase , lowercase ): """simpl...
55
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ...
193
0
"""simple docstring""" import sys import turtle def _snake_case ( UpperCAmelCase_ : tuple[float, float] , UpperCAmelCase_ : tuple[float, float] ): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def _snake_case ( UpperCAmelCase_ : ...
69
"""simple docstring""" def _snake_case ( UpperCAmelCase_ : int = 50 ): A__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length +...
69
1
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax...
55
import requests from bsa import BeautifulSoup def UpperCAmelCase_ ( _A = "AAPL" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = F'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}''' SCREAMING_SNAKE_CASE__ = BeautifulSoup(requests.get(_A ).text , ''...
314
0
'''simple docstring''' from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class lowerCamelCase ( lowercase_ ): '''simple docstring''' __snake_case = 'philschmid/bart-large-cnn-samsum' __snake_case = ( 'This is a tool that ...
358
'''simple docstring''' def __lowerCamelCase ( __snake_case : int ) -> bool: """simple docstring""" if p < 2: raise ValueError("""p should not be less than 2!""" ) elif p == 2: return True A__ : Any =4 A__ : ...
136
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = {'''configuration_focalnet''': ['''FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FocalNetConfig''']} tr...
89
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-...
73
0
"""simple docstring""" import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor...
150
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, Im...
150
1
UpperCamelCase = [ (1_000, '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'), ] def __lowerCamelCase ( snake_case__ ) -> i...
306
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 __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''sim...
133
0
_snake_case : int = 256 # Modulus to hash a string _snake_case : Any = 1000003 def a_ ( lowerCAmelCase_ : str, lowerCAmelCase_ : str ): __lowerCAmelCase = len(lowerCamelCase_ ) __lowerCAmelCase = len(lowerCa...
358
class _UpperCAmelCase : """simple docstring""" def __init__( self : Union[str, Any] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : int , lowerCAmelCase_ : Dict ) -> List[str]: __lowerCAmelCase = name __lowerCAmelCase = value ...
207
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase( metaclass=a_ ): '''simple docstring''' lowercase__ = ["transformers", "torch", "note_seq"] def __init__( self: Any, *a_: List[str], **...
64
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": UpperCAmelCase : Dict =argparse.ArgumentParser() parser.add_argument("""--dump_path""", default=None...
128
0
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --use...
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
1
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) __snake_case :List[Any] = pytest.mark.integration @pytest.mark.parametrize('''path''' , ...
49
'''simple docstring''' import random from .binary_exp_mod import bin_exp_mod def snake_case_ ( _lowerCAmelCase : Tuple , _lowerCAmelCase : Optional[Any]=1000 ) -> int: if n < 2: return False if n % 2 == 0: r...
23
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase ={ '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''], } try: if not is_torch_a...
355
"""simple docstring""" from typing import Dict, Iterable, 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, ...
77
0
from statistics import mean, stdev def A_ ( snake_case : Optional[int] , snake_case : Union[str, Any] = 3 ) -> list: '''simple docstring''' __UpperCamelCase = min(__lowerCAmelCase ) __UpperCamelCase = max(__lowerCAm...
328
"""simple docstring""" import colorsys from PIL import Image # type: ignore def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Union[str, Any] = x SCREAMING_SNAKE_CASE__ : Unio...
132
0
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCAmelCase__ ( a__ = True , *a__ , **a__ ) ->Dict: '''simple docstring''' if not is_tqdm_available(): raise ImportError("Accelerate...
63
import re def lowerCAmelCase__ ( a__ ) ->str: '''simple docstring''' if len(re.findall("[ATCG]" , a__ ) ) != len(a__ ): raise ValueError("Invalid Strand" ) return dna.translate(dna.maketrans("ATCG" , "TAGC" ) ) if __name__ == "__main__": import doctes...
63
1
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("""ignore""", category=UserWarning, module="""torch.optim.lr_scheduler""") class A__ : def __init__( se...
325
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger SCREAMING_SNAKE_CASE__ = get_logger(__name__) class A__ ( enum.Enum ): lowerCAmelCase__ : Dict = "all_checks" lowerCAmelCase__ : ...
325
1
from math import factorial def a( A : int , A : int , A : float ) -> float: """simple docstring""" if successes > trials: raise ValueError("successes must be lower or equal to trials" ) if trials < 0 or successes < 0: raise ValueError("the funct...
369
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCAmelCase ) class _lowercase ( lowerCAmelCase ): """simple docstring""" __A = ...
71
0
"""simple docstring""" import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common impor...
69
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def UpperCAmelCase ( ) -> int: snake_case_ = HfArgumentParser(UpperCAmelCase ) snake_case_ = parser.parse_args_into_dataclasses()[0] ...
69
1
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCamelC...
364
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import ...
176
0
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder lowercase_ : Union[str, Any] = "__DUMMY_TRANSFORMERS_USER__" lowercase_ : Dict = "Dummy User" lowercase_ : Optional[int] = "hf_hZEmn...
133
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Union[str, Any] = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b...
136
0
import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : Dict ...
277
import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, 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 ...
277
1
"""simple docstring""" class lowerCAmelCase_ : """simple docstring""" def __init__( self ): """simple docstring""" snake_case = {} # Mapping from char to TrieNode snake_case = False def snake_case ( self , lowe...
150
"""simple docstring""" import argparse import copy def lowerCAmelCase__ ( _UpperCamelCase : List[Any] ) -> str: """simple docstring""" snake_case = {} with open(_UpperCamelCase ) as f: for line in f: if lin...
150
1
from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowerCAmelCase__ :Optional[A...
185
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) lowerCAmelCase__ :Tuple = {'''configuration_beit''': ['''BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BeitConfig'''...
185
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if len(snake_case__ ) < k or k < 0: raise ValueError('''Invalid Input''' ) A : Any =...
3
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging ...
207
0
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): fr...
350
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins a : int = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Tuple: '''simple docstring''' for it...
72
0
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <us...
0
def _a ( a :int ) -> bool: a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
0
1
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORD...
166
"""simple docstring""" import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class lowerCamelCase ( lowerCAmelCase__ ): ...
166
1
"""simple docstring""" import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py UpperCAmelCase__ : str = '\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-j...
25
"""simple docstring""" import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class UpperCAmelCase_ : def __init__( self , a ) -> List[str]: if isinstance(a ...
77
0
import unittest from transformers import AutoTokenizer, FalconConfig, 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 Model...
216
def snake_case__ ( SCREAMING_SNAKE_CASE_ : float ): '''simple docstring''' if edge <= 0 or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError('Length must be a positive.' ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1...
216
1
'''simple docstring''' # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under ...
63
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase_ : List[str] = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/m...
63
1
import mpmath # for roots of unity import numpy as np class __lowercase : """simple docstring""" def __init__( self , A=None , A=None ) -> Union[str, Any]: # Input as list snake_case : Optional[int] = list(poly_a or [0] )...
370
import functools def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> int: # Validation if not isinstance(lowercase ,lowercase ) or not all(isinstance(lowercase ,lowercase ) for day in days ): raise ValueError("""The parameter days should be a list o...
176
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase_ = { '''configuration_altclip''': [ '''ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AltCLIPConfig''...
346
from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( ...
71
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class lowerCamel...
350
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import c...
299
0
def A_ ( A__ , A__ , A__ ) -> float: if principal <= 0: raise Exception('Principal borrowed must be > 0' ) if rate_per_annum < 0: raise Exception('Rate of interest must be >= 0' ) if years_to_repay <= 0 or not isinstance(A__ , A__ )...
99
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to ...
176
0
"""simple docstring""" import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if n...
172
"""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 .tokeniza...
172
1
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and ...
277
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a_ :Optional[Any] = {"configuration_reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConf...
277
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case : Union[str, Any] =logging.get_logger(__name__) __snake_case : Optional[int] ={ ...
94
__snake_case : Any ='\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' __snake_case : Tuple =[{'type':...
94
1
'''simple docstring''' import qiskit def UpperCAmelCase__ ( UpperCAmelCase_ : int = 2 ) -> qiskit.result.counts.Counts: __lowerCamelCase : str = qubits # Using Aer's simulator __lowerCamelCase : Optional[Any] = qiskit.Aer.get_backend('aer_simulator' ...
185
'''simple docstring''' 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 classe...
185
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : Tuple = logging.get_logger(__name__) _UpperCAmelCase : Optional[Any] = { """tiiuae/falcon-40b""": """https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json""", """tiiu...
359
import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from tr...
200
0
'''simple docstring''' import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class __UpperCAmelCase ...
42
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCAmelCase__ = logging.get_logger(__name__) # TODO: upload to AWS lowerCAmelCase__ = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/re...
72
0
"""simple docstring""" import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerT...
24
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArg...
24
1
'''simple docstring''' import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging lowerCamelCase = logging.get_logger(__name__)...
166
'''simple docstring''' import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class _UpperCamelCase ( A ): ...
166
1
'''simple docstring''' from typing import Any class __UpperCamelCase : def __init__( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =data lowerCamelCase_ =None def __repr__( self ): ...
6
'''simple docstring''' import math import random from typing import Any from .hill_climbing import SearchProblem def a_ ( __snake_case : str , __snake_case : bool = True , __snake_case : float = math.inf , __snake_case : float = ...
6
1
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_up...
216
import colorsys from PIL import Image # type: ignore def __UpperCamelCase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : int ): __a : Any = x __a : List[Any] = y for step in range(lowerCAmelCase__ ): # noqa: B007 __a : ...
216
1
"""simple docstring""" import math import os import sys def lowercase ( lowerCAmelCase__ : Dict ) -> str: __a = '' try: with open(_UpperCAmelCase , '''rb''' ) as binary_file: __a = binary_file.read() for dat in data: ...
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_efficientformer": [ "EFFICIENTFO...
11
0