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
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils...
373
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { '''tiiuae/falcon-40b''': '''https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.j...
373
1
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from...
583
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_confi...
583
1
def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> int: return number | (1 << position) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> int: return number & ~(1 << position) def snake_case (UpperCAmelCase__ , ...
57
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate....
57
1
"""simple docstring""" import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import Mask...
615
"""simple docstring""" def _lowercase ( __snake_case = 3 ,__snake_case = 7 ,__snake_case = 1_000_000 ) -> int: __lowerCAmelCase : Optional[Any] = 0 __lowerCAmelCase : List[str] = 1 for current_denominator in range(1 ,limit + 1 ...
615
1
'''simple docstring''' 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 YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verb...
209
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a = logging.get_logger(__name__) a = { '''facebook/s2t-small-librispeech-asr''': ( '''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config...
7
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.mod...
701
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def _a ( UpperCAmelCase ) -> bool: """simple docstring""" lowerCamelCase__ : int = int(number**0.5 ) return number == sq * sq def _a ( UpperCAmelCase ...
130
0
'''simple docstring''' def _A ( A__ = 1000 ): """simple docstring""" return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
41
import torch from diffusers import DiffusionPipeline class lowercase ( UpperCamelCase__ ): def __init__( self , _a , _a ) -> List[str]: super().__init__() self.register_modules(unet=_a , scheduler=_a ) def __call__( self ...
307
0
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertF...
707
'''simple docstring''' 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_FIL...
172
0
"""simple docstring""" import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints...
83
"""simple docstring""" def __snake_case ( __A : int , __A : int ) -> float: '''simple docstring''' return base * power(__A , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('Raise base to the power of exponent us...
265
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list ) -> list: '''simple docstring''' if len(SCREAMING_SNAKE_CASE_ ) < 2: return collection def circle_sort_util(SCREAMING_SNAKE_CASE_: list , SCREAMING_SNAKE_CASE_: int , SCREAMING_S...
702
lowerCAmelCase__ = """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/""" def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: bytes ) -> bytes: '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A__...
626
0
import numpy as np def lowerCamelCase__ (_UpperCAmelCase): return 1 / (1 + np.exp(-vector)) def lowerCamelCase__ (_UpperCAmelCase): return vector * sigmoid(_UpperCAmelCase) if __name__ == "__main__": import doctest doctest.testmod()
73
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _A = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise Op...
431
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(): from PIL import Image ...
58
'''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 not is...
58
1
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase_ ( snake_case__ ): Up...
668
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _UpperCAmelCase : str = logging.get_logger(__name__) _UpperCAmelCase : Dict = {"vocab_file": "vocab.json"} _UpperCAmelCase : Optiona...
668
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json', } class _lowercase ...
133
"""simple docstring""" def UpperCAmelCase ( a_ ): '''simple docstring''' try: lowerCamelCase : List[str] = float(a_ ) except ValueError: raise ValueError('Please enter a valid number' ) lowerCamelCase : Dict = decimal - int(a_ ) if ...
133
1
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar __a : Any = TypeVar('''T''') class UpperCAmelCase( Generic[T] ): ...
397
from __future__ import annotations import bisect def SCREAMING_SNAKE_CASE ( snake_case_ : list[int] , snake_case_ : int , snake_case_ : int = 0 , snake_case_ : int = -1 ): if hi < 0: snake_case__ : Any = len(snake_case_ ) while lo < hi: snake_case_...
297
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channe...
687
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __snake_case : Union[str, Any] = { 'configuration_falcon': ['FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FalconConfig'], } try: if not is_t...
687
1
def __snake_case ( _lowerCAmelCase : int ) -> bool: return str(_lowerCAmelCase ) == str(_lowerCAmelCase )[::-1] def __snake_case ( _lowerCAmelCase : int ) -> int: return int(_lowerCAmelCase ) + int(str(_lowerCAmelCase )[::-1] ) def...
454
def __snake_case ( _lowerCAmelCase : list , _lowerCAmelCase : list , _lowerCAmelCase : int ) -> int: if len(_lowerCAmelCase ) != len(_lowerCAmelCase ): raise ValueError("The length of profit and weight must be same." ) if max_weight <= 0:...
454
1
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node UpperCamelCase__ = 4 UpperCamelCase__ = 3 class _UpperCamelCase ( ...
700
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase__ : List[Any] = {"""configuration_sew""": ["""SEW_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SEWConfig"""]} try: if not is_torch_available(): raise ...
486
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase__ : Tuple = { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dp...
48
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, loggin...
555
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging....
721
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin im...
148
0
'''simple docstring''' def UpperCAmelCase__ ( UpperCAmelCase_ : list , UpperCAmelCase_ : list ) -> float: _validate_point(UpperCAmelCase_ ) _validate_point(UpperCAmelCase_ ) if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): ra...
13
'''simple docstring''' import re def _snake_case ( _SCREAMING_SNAKE_CASE : str ) -> bool: """simple docstring""" lowerCAmelCase = re.compile( R"""^(?:0|94|\+94|0{2}94)""" R"""7(0|1|2|4|5|6|7|8)""" R"""(-| |)""" R"""\d{7}$""" ) retur...
433
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType A_ = logging.ge...
360
def __UpperCamelCase ( a, a, a=False) ->Dict: if isinstance(a, a) and isinstance(a, a): lowerCamelCase__ = len(set_a.intersection(a)) if alternative_union: lowerCamelCase__ = len(a) + len(a) else: ...
360
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.ima...
161
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, Levi...
161
1
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _a ( __UpperCamelCase , ...
702
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __lowerCamelCase = logging.get_logger(__name__) def _a ( __UpperCamelCase=None , __UpperCamelCase=None ): return field(defa...
478
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], "tokenization_...
26
'''simple docstring''' import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from...
26
1
import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class _a ( lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCamelCase_ : Opti...
718
def lowerCamelCase_ ( _lowercase = 2_000_000 ) -> int: __A : str = [0 for i in range(n + 1 )] __A : int = 1 __A : Dict = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: ...
387
0
"""simple docstring""" import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassific...
626
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transfor...
626
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers...
707
from collections.abc import Callable def _UpperCAmelCase ( a : Callable[[float], float] , a : float , a : float ): snake_case__ = a snake_case__ = b if function(a ) == 0: # one of the a or b is a root for the function return a ...
99
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, ) _lowerCAmelCase : List[Any] = { "configuration_remb...
289
"""simple docstring""" import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transform...
289
1
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_model...
712
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : Union[str, Any] =logging.get_logger(__name__) __lowercase : List[Any] ={ """tanreinama/GPTSAN-2.8B-spout_is_uniform""": ( """https://huggingface.co/tanreinama/GPT...
550
0
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, ) if is_sentencepiece_available(): from ..ta.tokenizatio...
257
import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokeniza...
257
1
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor A_ : Any = logging.get_logger(__name__) class _a (__magic_name__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): warnings.wa...
64
def UpperCamelCase (lowercase_: int , lowercase_: int ) -> int: while second != 0: A__ : int = first & second first ^= second A__ : int = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() A_ : Optional[Any] ...
64
1
from __future__ import annotations def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> list[str]: if nth_term == "": return [""] UpperCamelCase_: List[str] = int(UpperCAmelCase__ ) UpperCamelCase_: Any = int(UpperCAmelCase_...
57
'''simple docstring''' 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 GenerationTesterMi...
502
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(...
719
def lowercase_ ( __snake_case : list ) -> list: '''simple docstring''' if any(not isinstance(__snake_case , __snake_case ) or x < 0 for x in sequence ): raise TypeError("Sequence must be list of non-negative integers" ) for _ ...
57
0
"""simple docstring""" 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 _lowerCAmelCase = logging.get_...
259
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_com...
259
1
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenize...
704
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { """configuration_nllb_moe""": [ """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NllbMoeConfig""", ] } try: if not is_torch_available(...
481
0
def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> float: if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(__snake_case ) * abs(__snake_case ) if __name__ == "__main__": import doctest docte...
108
from itertools import permutations def lowerCAmelCase__ ( _a : 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 snake_case_ : List[str] = [7, 11, 13, 17] for i, te...
568
0
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow lowerCAmelCase : List[str] = [ os.path.join(os.path.dirname(__file__), dirname) fo...
432
'''simple docstring''' lowerCAmelCase : Optional[Any] = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install ...
432
1
from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
479
'''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 n...
597
0
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPip...
711
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 __lowerCamelCase ( _lowerCAmelCase ...
129
0
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def _SCREAMING_SNAKE_CASE ( __snake_case ) -> str: _UpperCAmelCase = {} _UpperCAmelCase ...
108
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from...
514
0
'''simple docstring''' from collections import namedtuple import requests from lxml import html # type: ignore lowerCamelCase_ : Any = namedtuple('''covid_data''', '''cases deaths recovered''') def __magic_name__( _A = "https://www.worldometers.info/coronavirus/" ): '''simple ...
265
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docs...
265
1
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 Optional import huggingface...
684
def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Dict = word.split() def justify(_lowercase , _lowercase , _lowercase ) -> str: SCREAMING_SNAKE_CASE : Union[str, Any] = max_width - width ...
248
0
import math from datetime import datetime, timedelta def UpperCamelCase ( _A : Tuple )-> str: """simple docstring""" A__ = year % 19 A__ = year % 4 A__ = year % 7 A__ = math.floor(year / 100 ) A__ = math.floo...
703
def UpperCamelCase ( _A : list[list[int]] , _A : int , _A : int , _A : list[int] )-> bool: """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is n...
232
0
_lowerCAmelCase : dict[str, float] = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, } _lowerCAmelCase : dict[str, float] = { "km/h": 1.0, "m/s": 0.277777778, "mph": 0.621371192, "knot": 0.539956803, } def ...
242
import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuest...
242
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase = { 'configuration_conditional_detr': [ 'CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConditionalD...
702
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __lowerCamelCase : Optional[int] = TypeVar('T') class UpperCAmelCase ( Generic[T]): """simple docstring""" lowerCAmelCase_ = 42 ...
271
0
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTr...
89
'''simple docstring''' from typing import Union import fire import torch from tqdm import tqdm def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str = "cpu" , __A : Union[str, None] = None ) -> None: _SCREAMING_SNAKE_CASE = torch.load(__A , map_locati...
418
0
import math def __lowerCamelCase ( A__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All p...
171
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class SCREAMING_SNAKE_CASE_ (pl.LightningModule ): '''simple docstring''' def __init__( self : Any , __a ...
171
1
def SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase ): # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection snake_case__ = len(__lowerCAmelCase ) snake_case__ = max(__lowerCAmelCase ) snake_c...
276
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer ...
276
1
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class __UpperCamelCase ( _lowercase ): """simple docstring""" _lowercase : Optional[Any] = '''MCTCTFeatureExtractor''' _lowercase : str = '''AutoTokenizer...
716
def __a ( __UpperCAmelCase , __UpperCAmelCase ): # Check if the input is valid if not len(__UpperCAmelCase ) == len(__UpperCAmelCase ) == 3: raise ValueError('''Please enter a valid equation.''' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise...
148
0
from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_S...
99
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {'vocab_file': 'vocab.json'} _Uppe...
459
0
"""simple docstring""" import tensorflow as tf from ...tf_utils import shape_list class lowercase_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Optional[int] , _UpperCAmelCase : Dict , _UpperCAmelCase : Dict , _UpperCAmelCase : Li...
714
"""simple docstring""" import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def _snake_case ( _snake_case : List[Any] ) -> Any: '''simple do...
505
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
166
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__ = {"""configuration_opt""": ["""OPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OPTConfig"""]...
166
1
from collections import deque class UpperCAmelCase__ : def __init__( self ,A__ ,A__ ,A__ ): _A : int = process_name # process name _A : str = arrival_time # arrival time of the process # completion time...
713
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCamelCase : Dict =logging.get_logger(__name__) _UpperCamelCase : Optional[Any] ={ 'facebook/xmod-bas...
332
0
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class UpperCAmelCase__ ( unittest.TestCase , A_ ): '''simple docstring''' def lowerCAmelCase_ ( self : Optional[int] ): """simple docstring""" ...
322
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor UpperCamelCase__ = logging.get_logger(__name__) class UpperCAmelCase__ ( A_ ): '''simple docstring''' def __init__( self : int , *UpperCamelCase : ...
322
1
from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transf...
718
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A__ ( __UpperCAmelCase ): """simple docstring""" __A : Tuple = ['''image_processor''', '''tokenizer'''] __A : Any = ...
392
0
'''simple docstring''' 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....
588
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transforme...
588
1
from __future__ import annotations def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ): """simple docstring""" if partitions <= 0: raise ValueError('partitions must be a positive number!' ) if partitions > number_of_bytes: raise ValueError('partitions can not > number_of_bytes!'...
709
"""simple docstring""" from __future__ import annotations import collections import pprint from pathlib import Path def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" return "".join(sorted(__UpperCAmelCase ) ) def __lowerCAmelCase( __UpperCAmelCase ): ""...
283
0
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_co...
7
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, l...
374
0
import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def a__ (...
332
import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if ver...
332
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SN...
88
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_full_determinism() class...
412
0
"""simple docstring""" import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def A_ ( __UpperCamelCase : int ): def wrapper(*__UpperCamelCase : List[Any] , **__Upper...
704
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( __UpperCamelCase : str , __UpperCamelCase : dict ): lowercase = BeautifulSoup(requests.get(__UpperCamelCase , params=__UpperCamelCase ).content , '''html.parser''' ...
396
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_convbert import ConvBertTokenizer _UpperCamelCase : Any = logging.g...
541
from typing import TYPE_CHECKING from ...utils import _LazyModule _lowerCamelCase = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _lowerCamelCase ...
144
0
from __future__ import annotations def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[int] , __UpperCamelCase : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = len(Upper...
710
import os __lowerCamelCase : Union[str, Any] = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000} def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> int: """simple docstring""" SCREAMI...
379
0
import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common ...
219
import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_...
219
1
'''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 clas...
123
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase__ ( a ): '''simple docstring''' @staticmethod @abstractmethod def snake_case ( SCREAMING_SNAKE_CASE ) -> Optional[Any]: ...
123
1
"""simple docstring""" import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = None ,lowerCAmelCase__...
29
"""simple docstring""" import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() parser.add_argument( '''--check...
156
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from ut...
91
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easi...
91
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tens...
109
"""simple docstring""" from string import ascii_uppercase lowerCAmelCase__ = {str(ord(c) - 55): c for c in ascii_uppercase} def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if isinstance(SCREAMING...
645
0
"""simple docstring""" def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> int: """simple docstring""" __UpperCAmelCase , __UpperCAmelCase : str = len(UpperCamelCase ), len(grid[0] ) if ( ...
487
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .sche...
487
1
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCo...
10
import sys from collections import defaultdict class lowerCAmelCase_ : def __init__( self : Optional[int] ): _UpperCamelCase = [] def UpperCamelCase_ ( self : Any , _A : str ): return self.node_position[verte...
10
1
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configura...
46
import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline A = argparse.ArgumentParser('Stable Diffusion script with intel optimization', add_help=False) parser.add_argument('--dpm', action='store_true', help='En...
46
1
"""simple docstring""" def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ = " " ) ->list: """simple docstring""" __UpperCAmelCase : Tuple = [] __UpperCAmelCase : Union[str, Any] = 0 for index, char in enumerate(Uppe...
522
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache....
522
1
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYa...
711
def __lowerCAmelCase ( UpperCamelCase ) -> bool: if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(UpperCamelCase ) == 0: raise ValueError('''Input list must be a non empty lis...
470
0
'''simple docstring''' import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class UpperCAmelCase_ ( __...
94
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher...
368
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): ...
714
"""simple docstring""" import functools def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ): """simple docstring""" if not isinstance(__UpperCAmelCase ,__UpperCAmelCase ) or not all(isinstance(__UpperCAmelCase ,__UpperCAmelCase ) for day in days ): raise ValueErr...
283
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, Sta...
696
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=A__ ) class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = field(default=''...
696
1
'''simple docstring''' def _a ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(lowerCamelCase_ ) ) def _a ( lowerCamelCase_ , lowerCamelCase_ , lo...
718
'''simple docstring''' from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone ...
136
0
"""simple docstring""" def _UpperCamelCase ( UpperCamelCase ) -> bool: """simple docstring""" if p < 2: raise ValueError("p should not be less than 2!" ) elif p == 2: return True __UpperCAmelCase : List[Any] = 4 __UpperCAme...
77
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class a__ ...
77
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_...
622
import torch from diffusers import StableDiffusionPipeline a_ = """path-to-your-trained-model""" a_ = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("""cuda""") a_ = """A photo of sks dog in a bucket""" a_ = pipe(prompt, num_inference_steps=50, guidance_s...
622
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 TokenizerTesterMix...
536
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __lowerCAmelCase = TypeVar("T") class __SCREAMING_SNAKE_CASE (Generic[T] ): """simple docstring""" def __init__( self , UpperCamel...
536
1
'''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, TrainerCall...
434
'''simple docstring''' from __future__ import annotations from math import gcd def lowercase__ ( __lowercase : int , __lowercase : int = 2 , __lowercase : int = 1 , __lowercase : int = 3 , ) -> int | None: """simple...
434
1
"""simple docstring""" from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def _lowerCamelCase ( UpperCAmelCase_ : int ) -> int: """simple docstring""" A__ = prime_factors(UpperCAmelCase...
104
def lowerCamelCase__ ( snake_case_ : str , snake_case_ : list[str] ) -> str: __snake_case = '''''' for word_or_phrase in separated: if not isinstance(snake_case_ , snake_case_ ): raise Exception('''join() accepts only strings to be joine...
592
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class snake_case_ ( _...
701
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_...
240
0
"""simple docstring""" import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image ...
49
"""simple docstring""" __UpperCAmelCase : List[str] = {str(digit): digit**5 for digit in range(10)} def A ( _A ): """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(_A ) ) def A ( ): """simple docstring""" return...
584
0
'''simple docstring''' import argparse import json import subprocess def lowercase__ ( __lowercase : int , __lowercase : Any ) -> List[Any]: """simple docstring""" __UpperCamelCase = [] __UpperCamelCase = ( F'''curl -H...
434
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch ...
434
1
"""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, MaskFormerImageProcess...
560
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Any , __lowerCAmelCase : int ) -> Tuple: # noqa: E741 ...
369
0
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lic...
715
"""simple docstring""" import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch lowerCAmelCase : Optional[Any] ...
533
0
'''simple docstring''' from typing import Dict, Optional import numpy as np import datasets A : Dict = ''' IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth. For binar...
349
"""simple docstring""" import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @requ...
46
0
'''simple docstring''' def UpperCAmelCase_ ( lowerCamelCase_ ): """simple docstring""" lowerCAmelCase__ : Optional[int] = len(lowerCamelCase_ ) for i in range(length - 1 ): lowerCAmelCase__ : Optional[Any] = i for k in range(i + 1 , lowerCamelCase_ ): if col...
568
'''simple docstring''' import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """vocab_file""": """vocab.t...
568
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case :str =logging.get_logger(__name__) __snake_case :Tuple ={ 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json' ...
106
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs ...
3
0
"""simple docstring""" import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import Accele...
706
"""simple docstring""" import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class UpperCamel...
536
0
'''simple docstring''' import os import pytest from transformers.dynamic_module_utils import get_imports _lowerCAmelCase = ''' import os ''' _lowerCAmelCase = ''' def foo(): import os return False ''' _lowerCAmelCase = ''' def foo(): def bar(): if True: ...
565
'''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_opt''': ['''OPT_PRETRAINED_CONFIG_...
565
1
from ...processing_utils import ProcessorMixin class a__ ( __SCREAMING_SNAKE_CASE ): _A = ["image_processor", "feature_extractor"] _A = "TvltImageProcessor" _A = "TvltFeatureExtractor" def __init__( self : Union[str, Any] , ...
702
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 Accelera...
584
0
'''simple docstring''' import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def __UpperCAmelCase ( __magic_name__ )-> Union[str, Any]: """simple docstring""" snake_case...
653
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase : Optional[int] = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConf...
468
0
import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): ...
717
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTest...
203
0
from __future__ import annotations from fractions import Fraction def a_ ( __magic_name__ , __magic_name__ ) -> Any: """simple docstring""" return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def ...
598
import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL UpperCamelCase__ = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def lowerCamelCas...
268
0
"""simple docstring""" 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_for...
712
"""simple docstring""" import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __a ( _lowerCAmelCase ): UpperCamelCase_ : Any = (EulerDiscreteScheduler,) UpperCamelCase...
556
0
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, re...
277
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained mod...
466
0
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaT...
355
'''simple docstring''' import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.dat...
355
1