code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_t...
283
import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC SCREAMING_SNAKE_CASE :Union[str, Any] = parse(importlib.metadata.version('''torch''')) def _lowerCAmelCase ( lowerCAmelCase_ :Union...
283
1
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from path...
701
"""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_available(...
549
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, ...
11
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(...
234
0
"""simple docstring""" from PIL import Image def lowercase (_snake_case ,_snake_case ) -> Image: '''simple docstring''' def brightness(_snake_case ) -> float: return 128 + level + (c - 128) if not -2_5_5.0 <= level <= 2_5_5.0: raise ValueError("level must be between -255.0 ...
228
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar _A = TypeVar("T") class __UpperCAmelCase ( Generic[T] ): """simple docstring""" _snake_case : deque[T] # Cache store of keys ...
228
1
'''simple docstring''' def A_ ( _lowerCAmelCase : list[list] ): """simple docstring""" _lowerCamelCase : List[str] = current_set.copy() for row_index, row in enumerate(_lowerCAmelCase ): _lowerCamelCase : Optional[int] = row[0] ...
44
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvisio...
88
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_...
709
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__...
228
0
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from dataset...
216
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from dataset...
216
1
from typing import Dict, Optional import numpy as np import datasets _lowerCamelCase = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-cl...
613
import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, ...
613
1
"""simple docstring""" import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def __A ( a_ :BertModel , a_ :str , a_ :str) -> str: __a : List[str] = ('''dense.weigh...
52
import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def _A ( __snake_c...
693
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import ...
719
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase_ ( lowerCamelCase_ ...
435
0
from scipy.stats import pearsonr import datasets a_ = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally...
221
import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from .....
221
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase = { "configuration_roformer":...
707
"""simple docstring""" import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, ...
14
0
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ......
31
# Copyright (c) 2021-, NVIDIA CORPORATION. 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 ap...
492
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator...
180
SCREAMING_SNAKE_CASE__ : str = """Alexander Joslin""" import operator as op from .stack import Stack def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :Optional[int] = {'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': ...
180
1
import math import qiskit def _UpperCamelCase (a__ :int = 1 , a__ :int = 1 , a__ :int = 1 ): """simple docstring""" if ( isinstance(a__ , a__ ) or isinstance(a__ , a__ ) or isinstance(a__ , a__ )...
619
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird i...
619
1
def a_ ( lowerCAmelCase_ : int, lowerCAmelCase_ : Dict ): __lowerCAmelCase = (boundary[1] - boundary[0]) / steps __lowerCAmelCase = boundary[0] __lowerCAmelCase = boundary[1] __lowerCAmelCase = make_points(lowerCamelCase__, lower...
710
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _snake_case : str = logging.get_logger(__name__) _snake_case : Optional[Any] ...
421
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer a =logging.get_logger(__name__) a ={"""vocab_file"""...
652
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 a =logging.get_logger(__name__) a ="""▁""" a ={"""vocab_file""": """...
652
1
'''simple docstring''' import argparse import math import traceback import dateutil.parser as date_parser import requests def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE_ :int = {} SCREAMING_SNAKE_CASE_ :Optional[int] = job['started_at'] ...
233
'''simple docstring''' from math import sqrt def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE = 100_0000 ): SCREAMING_SNAKE_CASE_ :int = 0 SCREAMING_SNAKE_CASE_ :int = 0 SCREAMING_SNAKE_CASE_ :int while num_cuboids <= limit: max_cuboid_size += 1 for su...
233
1
'''simple docstring''' from __future__ import annotations def __lowercase ( __lowercase ) -> int: '''simple docstring''' _A = len(UpperCamelCase__ ) // 2 # choose the middle 3 elements _A = lst[m - 1 : m + 2] # if middle element is peak ...
330
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> int: def count_of_possible_combinations(UpperCamelCase__ ) -> int: if target < 0: return 0 if target == 0: return 1 ...
546
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet impor...
683
from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCamelCase ( snake_case__ , snake_case__): lowerCAmelCase_ : Optional[int] = list(snake_case__) lowerCAmelCase_ : Tuple = list(snake_case__) lowerCAmel...
683
1
'''simple docstring''' import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transforme...
69
"""simple docstring""" import re def lowerCamelCase_( _lowerCamelCase ) -> str: '''simple docstring''' if len(re.findall("[ATCG]" , _lowerCamelCase ) ) != len(_lowerCamelCase ): raise ValueError("Invalid Strand" ) return dna.translate(...
46
0
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class UpperCamelCase__ ( __mag...
650
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: ...
650
1
from itertools import permutations def _a ( __UpperCamelCase : tuple ): if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False lowerCAmelCase__ : List[str] = [7, 11, 13, 17] for i, test...
233
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar A__ : Dict = TypeVar("""T""") def _a ( __UpperCamelCase : int ): return (position - 1) // 2 def _a ( __UpperCamelCase : int ): return (2 * position) + 1 def _a ( ...
233
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor _A = logging.get_logger(__name__) class _lowerCamelCase ( a_ ): def __init__( self : str , *UpperCamelCase : Dict , **UpperCamel...
708
"""simple docstring""" def lowercase_ ( __UpperCAmelCase = 100_0000 ) -> int: lowerCAmelCase__ : int = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1...
507
0
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, 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_available(): import ja...
37
import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase_ ( lowercase , unittest.TestCase ): __lo...
147
0
from ..utils import DummyObject, requires_backends class A__ ( metaclass=__lowerCamelCase): A_ : Any = ['flax'] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): requires_backends(self , ['flax'] ) @classmethod def __lowerCamelCase ( cl...
706
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase = False ): if not isinstance(_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : str = F"Expected string as input, found {type(_UpperCamelCase )}" raise ValueError(_UpperCamelCase ) if not i...
549
0
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_image if is_torch_availa...
100
"""simple docstring""" # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def _lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" _lowercase: int = { '''en''': '''Machine learning is great, is...
353
0
def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :Tuple = 1 __magic_name__ :Any = 2 while i * i <= n: __magic_name__ :str = 0 while n % i == 0: n //= i multiplicity += 1 ...
180
from __future__ import annotations from typing import Any class lowerCamelCase_ : def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 0 ): """simple docstring""" __magic_name__ , __magic_name__ :Any ...
180
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_ava...
623
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, Au...
623
1
import math import random from typing import Any from .hill_climbing import SearchProblem def a_ ( lowerCAmelCase_ : str, lowerCAmelCase_ : bool = True, lowerCAmelCase_ : float = math.inf, lowerCAmelCase_ : float = -math.inf, lowerCAmelCase_ : float = math.inf, lo...
421
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, 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_available(): impor...
421
1
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCAmelCase = logging.get_logger(__name__) _lo...
569
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vi...
426
0
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def UpperCamelCase...
707
"""simple docstring""" from sklearn.metrics import matthews_corrcoef import datasets __A = """ 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 takes into acco...
173
0
'''simple docstring''' import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPM...
138
'''simple docstring''' import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerC...
138
1
'''simple docstring''' from __future__ import annotations class _lowerCAmelCase : """simple docstring""" def __init__( self , _lowerCamelCase ) -> Dict: A_ : List[Any] = TypeError( """Matrices must be formed from a list of zero or m...
385
'''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 UpperCamelCase__ : str ...
385
1
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np ...
119
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available...
119
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, r...
521
'''simple docstring''' import math import sys def _lowerCamelCase ( lowercase : str ) -> str: _a = "" try: with open(lowercase , "rb" ) as binary_file: _a = binary_file.read() for dat in data: _a ...
521
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_REC...
665
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import...
665
1
import random class SCREAMING_SNAKE_CASE__ : '''simple docstring''' @staticmethod def _lowerCAmelCase ( lowerCamelCase__ ): A : Any = [ord(lowerCamelCase__ ) for i in text] A : str = [] A : Dict = [] for i in plain: ...
520
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_co...
520
1
import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, requ...
141
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def lowerCamelCase_ ( __UpperCamelCase = "" ): A_ = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250''' A_ = BeautifulSoup(requests.get(__UpperCamelCase ).text ...
141
1
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_f...
692
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase ...
692
1
"""simple docstring""" from collections.abc import Iterable from typing import Generic, TypeVar a : Union[str, Any] = TypeVar('_T') class lowercase(Generic[_T] ): def __init__( self , __SCREAMING_SNAKE_CASE = None ) -> None: """si...
273
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets _UpperCamelCase = '''\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul A...
146
0
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): A__ = HfArgumentParser(lowercase__ ) A__ = parser.parse_args_into_dataclasses()[0] A__ = TensorFlowBenc...
719
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForCon...
500
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 ): if not is_tqdm_available(): raise ImportError("Accelerate's `tqdm` module requires `tqdm` to be i...
162
def _UpperCAmelCase ( UpperCAmelCase : int = 600_851_475_143 ): """simple docstring""" try: __lowerCamelCase : Any = int(UpperCAmelCase ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable...
519
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_callback, get_e...
701
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging _snake_case : Optional[Any] = logging.get_logger(__name__) _snake_case : Optional[Any] = { 'Visual-Attention-Network/van-base': ( 'https://huggingface.co/Visual-Attention-Network/va...
524
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lower...
202
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 AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def lowerCAmelCase( SCREAMING_SNAKE_CAS...
628
0
import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_C...
563
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' A_ = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _lowerCamelCase ...
563
1
'''simple docstring''' from __future__ import annotations from math import pow, sqrt def _snake_case ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ) -> dict[str, float]: """simple docstri...
433
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def _snake_case ( _SCREAMING_SNAKE_CASE...
433
1
"""simple docstring""" import argparse import os import torch from transformers.utils import WEIGHTS_NAME lowerCAmelCase__ = ['''small''', '''medium''', '''large'''] lowerCAmelCase__ = '''lm_head.decoder.weight''' lowerCAmelCase__ = '''lm_head.weight''' def a_...
681
"""simple docstring""" def a__ ( SCREAMING_SNAKE_CASE : int = 1_0_0_0 ): '''simple docstring''' return sum(e for e in range(3 , SCREAMING_SNAKE_CASE ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(F"{solution() = }")
681
1
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class __lowercase ( __lowerCamelCase ): snake_case_ = """""" snake_case_ ...
65
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a_ = { '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''...
480
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def _SCREAMING_SNAKE_CASE ( snake_case_ ): _lowercase = SwinConfig(image_size=192 ) if "base" in model_name: _...
572
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( snake_case_ ): _lowercase = int(snake_case_ ) if n_element < 1: _lowercase = ValueError("""a should be a positive number""" ) raise my_error _lowercase = [1] _lowercase , _lowercase , _lowercase = (0, 0, 0) ...
572
1
from math import factorial lowercase : dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def snake_case__ ( lowerCamelCase_ ): if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError('''Parameter number must be...
542
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, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEA...
542
1
import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from trans...
203
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel _snake_case : int = { "text_branch": "text_model", "audio_branch": "audio_model.audio_encoder", "attn": "attention.self", "self.proj": "output.d...
203
1
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase_ ( a_ ): def __init__( self : int, _snake_case : Dic...
349
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf...
349
1
import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def A__ ( __A , __A , __A ): '''simple docstring''' if g...
709
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, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, ...
15
0
import numpy as np class _A : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Di...
68
'''simple docstring''' import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def _snake_case ( ) -> Union[str, Any]: raise RuntimeError('''CUDA out...
90
0
'''simple docstring''' import argparse import json 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_wa...
113
'''simple docstring''' import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging __A =logging.get_logger(__name__) def _UpperCamelCase ( UpperCamelCase__ ): UpperCAme...
113
1
'''simple docstring''' import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) lowerCAmelCase__ : T...
347
'''simple docstring''' import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configura...
347
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_input...
708
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs if is_torch_available(): ...
208
0
# flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_...
558
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments ...
311
0
"""simple docstring""" import warnings warnings.warn( "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: " "`from accelerate import find_executable_batch_size` to avoid this warning.", FutureWarning, )
625
"""simple docstring""" 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_configu...
625
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOu...
529
from __future__ import annotations def a__ ( A_, A_, A_, A_ ): '''simple docstring''' if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): __magic_name__ , __magic_name__ = array[indexa], a...
529
1
'''simple docstring''' import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin ...
13
'''simple docstring''' def __magic_name__ ( __UpperCAmelCase = 1 , __UpperCAmelCase = 1000 ) -> int: '''simple docstring''' __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 0 for divide_by_number in range(__UpperCAm...
13
1
'''simple docstring''' # Imports import numpy as np class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None...
13
__UpperCamelCase : str = {str(digit): digit**5 for digit in range(10)} def a_ ( _A ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(_A ) ) def a_ ( ) -> int: """simple docstri...
328
0
import torch from diffusers import DiffusionPipeline class _SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): def __init__( self : List[Any] , UpperCamelCase : Dict , UpperCamelCase : Union[str, Any] )->Optional[int]: super().__init__() self.register_modu...
719
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_ut...
447
0
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): A_ : Optional[int] ={ '''linear''': PIL.Image.Resampling.BILINEAR, '''b...
274
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder snake_case_ = datasets.utils.logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ (folder_based_builder.FolderBasedBuilderConfig ): __lowerCamelC...
164
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : List[str] = logging.get_logger(__name__) A_ : Union[str, Any] = { """google/pix2struct-textcaps-base""": ( """https://h...
718
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 A_ : List...
32
0
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging __magic_name__ =logging.get_logger(__name__) __magic_name__ =r''' Args: input_ids (`torch.LongTensor` of shape `(...
415
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs ...
415
1
'''simple docstring''' def snake_case ( a_ : int = 4_000_000 ) -> int: """simple docstring""" UpperCamelCase_ : Any = [] UpperCamelCase_ , UpperCamelCase_ : Union[str, Any] = 0, 1 while b <= n: if ...
543
'''simple docstring''' import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from t...
543
1
'''simple docstring''' import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_e...
489
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def _lowerCamelCase (__lowerCamelCase : Dict ) -> Tuple: a__ = [ "encoder.version", "decoder.version", ...
489
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, Aut...
265
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor lowerCamelCas...
265
1
"""simple docstring""" import numpy # List of input, output pairs __SCREAMING_SNAKE_CASE = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) __SCREAMING_SNAKE_CASE = (((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) __SCREAMING_SNA...
388
"""simple docstring""" 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 AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_u...
388
1
'''simple docstring''' import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.tes...
489
'''simple docstring''' def __a(SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise TypeError("Input value must be an 'int' type" ) _lowerCAmelCase = 0 while number: p...
489
1
'''simple docstring''' import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ : str = logging.get_lo...
48
'''simple docstring''' import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy fr...
72
0
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def UpperCame...
72
import math from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str ={ '''facebook/data2vec-base-960h''': '''https://huggingface.co/facebook/data2vec-a...
72
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase : Any = { 'configuration_altclip': [ 'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AltCLIPCon...
50
'''simple docstring''' from PIL import Image def A__ ( __lowerCAmelCase : Image , __lowerCAmelCase : float ): def brightness(__lowerCAmelCase : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: rai...
50
1
'''simple docstring''' 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,...
324
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, s...
324
1
import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) UpperCamelCase = logging.getLogger() def lowerCamelCase_ ...
520
from math import isqrt, loga def lowerCamelCase_ ( _lowercase ) -> list[int]: __A : Dict = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , _lowercase , _lowercas...
520
1
import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class a_( _UpperCAmelCase ): """simple docstring""" __snake_case : Optional[int] =(EulerDiscreteScheduler,) __snake_case :...
705
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup __UpperCAmelCase = logging.get_logger(__name__) class a_( lowe...
259
0
from queue import PriorityQueue from typing import Any import numpy as np def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , S...
39
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase__ : str = { 'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'], 'processing_git': ['GitProcessor'...
614
0
class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self : List[str] , lowerCamelCase : Any , lowerCamelCase : Dict , lowerCamelCase : List[str] ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = name ...
402
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutp...
402
1
'''simple docstring''' from sklearn.metrics import fa_score import datasets __a: Any = """\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n""" __a: List[str] = """\nArgs:\n predictions...
152
"""simple docstring""" def A_ ( lowercase ) -> int: """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def A_ ( lowercase ) -> bool: """simple docstring""" UpperCAmelCase_ : str ...
470
0
'''simple docstring''' import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest...
159
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Opti...
159
1
'''simple docstring''' import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM...
672
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mode...
205
0
'''simple docstring''' from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration __UpperCAmelCase = '''facebook/wmt19-en-de''' __UpperCAmelCase = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master mode...
718
'''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 __UpperCAmelCase = False class a__ ...
98
0
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import Tokenizer...
415
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, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, ...
415
1
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_commo...
360
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class SCREAMING_SNAKE_CASE_ ( datasets.BeamBasedBuilder ): """simple docstring""" def __magic_...
360
1
import datasets __UpperCAmelCase = '''\ @InProceedings{conneau2018xnli, author = "Conneau, Alexis and Rinott, Ruty and Lample, Guillaume and Williams, Adina and Bowman, Samuel R. and Schwenk, Holger and S...
40
"""simple docstring""" import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class lowerCamelCase__ ( lowerCamelCase_ ): @require_torch def lowerCamelCase_ ...
134
0
'''simple docstring''' from ...processing_utils import ProcessorMixin class SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCAmelCase__ = '''SpeechT5FeatureExtractor''' UpperCAmelCase__ = '''SpeechT5Tokenizer...
707
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import l...
204
0
'''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 a : Optional[Any] = logging.get_logger(__name_...
69
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_image i...
86
0
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ......
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase : List[Any] = { ...
293
1
import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp ...
16
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conv...
16
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a = logging.get_logger(__name__) a = { "naver-clova-ix/donut-base": "https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json", # See all Donut models at htt...
13
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a = {"configuration_sew": ["SEW_PRETRAINED_CONFIG_ARCHIVE_MAP", "SEWConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvail...
13
1
'''simple docstring''' import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_...
517
'''simple docstring''' # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
517
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 Config...
704
from __future__ import annotations _lowerCAmelCase = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] _lowerCAmelCase = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def lowercase ( _a ) -> list[float]: UpperCAmelCase_: Dict = [] U...
306
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A = {'''configuration_xlnet''': ...
52
'''simple docstring''' def lowerCamelCase__ ( a ): if number < 0: raise ValueError('number must not be negative' ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
356
0
def lowerCamelCase_(lowerCamelCase_ ) -> List[str]: UpperCAmelCase = set() # To detect a back edge, keep track of vertices currently in the recursion stack UpperCAmelCase = set() return any( node not in visited and depth_first_search(__lowercase ...
704
def lowerCamelCase_(lowerCamelCase_ = 600_851_475_143 ) -> int: try: UpperCAmelCase = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError...
457
0
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit ...
16
'''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 rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, Imag...
109
0
'''simple docstring''' def __UpperCamelCase ( _lowerCAmelCase = 6008_5147_5143 ) -> int: """simple docstring""" try: A : Optional[int] = int(SCREAMING_SNAKE_CASE_ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castab...
703
import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerI...
520
0
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor __lowercase = logging.get_logger(__name__) class _lowercase ( __lowerCamelCase ): def __init__( self : Optional[Any] , *lowerCamelCase__ : Optional[int] , **lower...
203
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib __lowercase = { """debug""": l...
203
1
# Copyright 2022 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 ap...
710
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __UpperCAmelCase : Tuple = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable...
57
0