code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import os import time import numpy as np import onnxruntime as ort lowerCAmelCase__ = '''1''' lowerCAmelCase__ = '''0''' lowerCAmelCase__ = '''1''' lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = ort.GraphOptimizationLevel.ORT_DI...
41
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) ...
6
0
'''simple docstring''' import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin A_ = get_tests_dir("fixtures/spiece.model") ...
42
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class Up...
6
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase = logging.get_logger(__name__) lowerCAmelCase = { 'junnyu/roformer_chinese_small': 'https://hug...
43
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""P...
6
0
'''simple docstring''' import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sq...
44
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safet...
6
0
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, ...
45
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""...
6
0
"""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 ...
46
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelC...
6
0
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrateg...
47
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailabl...
6
0
'''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 ...
48
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamel...
6
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : Optional[Any] = { 'configuration_upernet': ['UperNetConfig'], } try: if not is_torch_available(): raise ...
49
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Enco...
6
0
'''simple docstring''' from __future__ import annotations def A__ ( __lowerCAmelCase : tuple[int, int] , __lowerCAmelCase : int ): lowerCamelCase__ , lowerCamelCase__ = position lowerCamelCase__ = [ (y + 1, x + 2), (y...
50
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_byte...
6
0
'''simple docstring''' import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple=7 ) -> Dict: """simple docstring""" UpperCA...
51
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function:...
6
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
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, SwinConfig from transformers.utils import logg...
6
0
def a_ ( lowerCAmelCase_ : float, lowerCAmelCase_ : float, lowerCAmelCase_ : float, lowerCAmelCase_ : float, lowerCAmelCase_ : float, ): __lowerCAmelCase = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p i...
53
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCa...
6
0
def a__ ( lowercase__ , lowercase__ ): '''simple docstring''' return abs(lowercase__ ) if a == 0 else greatest_common_divisor(b % a , lowercase__ ) def a__ ( lowercase__ , lowercase__ ): '''simple docstring''' ...
54
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 AcceleratorState from accelerate.test_util...
6
0
def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" if not isinstance(a_ , a_ ): __A = F'''Input value of [number={number}] must be an integer''' raise TypeError(a_ ) if number < 0: return False __A = number * num...
55
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutp...
6
0
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _a : str = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD...
56
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor...
6
0
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo...
57
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import R...
6
0
"""simple docstring""" import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class _lowerCAmelCa...
58
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCame...
6
0
import numpy as np def lowerCAmelCase_ ( __a ) -> np.array: """simple docstring""" return 1 / (1 + np.exp(-vector )) def lowerCAmelCase_ ( __a ) -> np.array: """simple docstring""" return vector * sigmoid(1.7_0_2 * vector ) if...
59
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for...
6
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...
60
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import d...
6
0
import cva import numpy as np class __lowerCamelCase : """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: if k in (0.04, 0.06): lowerCAmelCase__ ...
61
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = ...
6
0
from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def lowerCamelCase__ ( lowercase , lowercase , lowercase = "x" , lowercase = 10**-10 , lowercase = 1 , ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = sy...
62
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we ...
6
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a : List[Any] = logging.get_logger(__name__) a : List[str] = { "sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json", # See all V...
63
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) ...
6
0
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def A__ ( ): SCREAMING_SNAKE_CASE__: str= ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' ...
64
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class Up...
6
0
"""simple docstring""" import random def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : List[str] = [], [], [] for element in data: if element < pivot: ...
65
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""P...
6
0
import numpy as np UpperCamelCase = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] class lowerCAmelCase_ : def __init__( self ): _lowercase : Any ...
66
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safet...
6
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def SCREAMING_SNAKE_CASE__ ( snake_case__ :str ) ->...
67
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""...
6
0
import comet # From: unbabel-comet import torch import datasets __A = datasets.logging.get_logger(__name__) __A = "\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n title = {Unbabel's Participation in the WMT20 Me...
68
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelC...
6
0
'''simple docstring''' from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar a : str = TypeVar('''KEY''') a : Tuple = TypeVar('''VAL''') @dataclass(frozen=_UpperCamelCase , slots=_...
69
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailabl...
6
0
def _SCREAMING_SNAKE_CASE ( lowercase : str , lowercase : bool = False ): '''simple docstring''' if not isinstance(lowercase , lowercase ): lowerCamelCase_ = f"""Expected string as input, found {type(lowercase )}""" ...
70
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamel...
6
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """...
71
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Enco...
6
0
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, requ...
72
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_byte...
6
0
def lowerCamelCase__ (): return [ a * b * (1000 - a - b) for a in range(1 , 999) for b in range(_UpperCAmelCase , 999) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(f"""{solution() = }""")
73
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function:...
6
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 lowercase_ = logging.get_logger(__name__) lowercase_ = { """hustvl/yolos-small""": """https:/...
74
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, SwinConfig from transformers.utils import logg...
6
0
'''simple docstring''' from __future__ import annotations def a__ ( lowerCAmelCase__ ) -> list[int]: return [ord(lowerCAmelCase__ ) - 96 for elem in plain] def a__ ( lowerCAmelCase__ ) -> str: return "".join(chr(elem + 96 ) for elem in encod...
75
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCa...
6
0
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer a_ = lo...
76
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 AcceleratorState from accelerate.test_util...
6
0
"""simple docstring""" def _UpperCamelCase ( UpperCamelCase ) -> float: """simple docstring""" __UpperCAmelCase : List[Any] = 0 while len(UpperCamelCase ) > 1: __UpperCAmelCase : Optional[int] = 0 # Consider...
77
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutp...
6
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[str] ={ 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-...
78
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor...
6
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { """huggingface/informer-tourism-monthly""": ( ...
79
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import R...
6
0
import math def snake_case ( lowerCamelCase ): '''simple docstring''' __lowercase = [] __lowercase = 2 __lowercase = int(math.sqrt(lowerCamelCase ) ) # Size of every segment __lowercase = [True] * (end + 1) __lowercase = ...
80
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCame...
6
0
# Algorithm for the pigeonhole sorting def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Optional[Any] = min(__lowerCamelCase ) # min() finds the minimum value __snake_case : Any = max(__lowerCamelCase ) # max() finds the max...
81
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for...
6
0
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments lowerCamelCase = logging.getLogger(__name__) @dataclass class lowercase__ ( SC...
82
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import d...
6
0
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformer...
83
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = ...
6
0
from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, require_torch_min...
84
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we ...
6
0
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class snake_case ( UpperCamelCase_ ): lowercase_ = (DPMSolverSDESched...
85
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) ...
6
0
def __snake_case ( __UpperCamelCase : int = 100 ): """simple docstring""" A_ = n * (n + 1) * (2 * n + 1) / 6 A_ = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"{solution() = }...
86
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class Up...
6
0
import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowerCamelCase : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Any , ...
87
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""P...
6
0
"""simple docstring""" def _snake_case ( __snake_case : str ): """simple docstring""" _lowerCamelCase : Any = 0 # if input_string is "aba" than new_input_string become "a|b|a" _lowerCamelCase : List[Any] = """""" _lowerCamelCase : ...
88
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safet...
6
0
SCREAMING_SNAKE_CASE : Tuple = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_b...
89
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""...
6
0
'''simple docstring''' import itertools import math def _snake_case ( A ) -> 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 n...
90
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelC...
6
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_time_series_transformer''': [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimeSeriesTransform...
91
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailabl...
6
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, DistilB...
92
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamel...
6
0
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return number | (1 << position) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return number & ~(1 << position)...
93
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Enco...
6
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
94
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_byte...
6
0
"""simple docstring""" from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def snake_case ( A__ ,A__ ,A__ = None ): if version.parse(hfh.__version__ ).release < version.parse("0.11.0" ).release: # old versions of h...
95
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function:...
6
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy __lowerCamelCase ...
96
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, SwinConfig from transformers.utils import logg...
6
0
import requests def a ( snake_case__: str , snake_case__: str ): '''simple docstring''' lowercase_ = {'''Content-Type''': '''application/json'''} lowercase_ = requests.post(snake_case__ , json={'''text''': message_body} , headers=snake_case__ ) if ...
97
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCa...
6
0
'''simple docstring''' from __future__ import annotations from typing import TypedDict class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" _snake_case : str _snake_case : int def a__ ( lowercase : str ) -> list...
98
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 AcceleratorState from accelerate.test_util...
6
0
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE = importlib.util.find_spec('s3fs') is not None if _has_safs: from .s...
99
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutp...
6
0
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_configuration_common import Co...
100
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor...
6
0
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig lowerCAmelCase__ : Optional[Any] =logging.get_logger(__name__) lowerCAmelCase__ : Dict ...
101
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import R...
6
0
"""simple docstring""" __magic_name__ : dict[tuple[int, int, int], int] = {} def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # if we are absent twice, or late 3 consecutive days, # no furthe...
102
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCame...
6
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''', } ...
103
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for...
6
0
"""simple docstring""" from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def _lowerCamelCase ( UpperCAmelCase_ : int ) -> Optional[Any]: """simple docstring""" def is_in_ci...
104
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import d...
6
0
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that...
105
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = ...
6
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_table, ) fr...
106
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we ...
6
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( __snake_case : str , __snake_case : str ): _A = len(__snake_case ) _A = [] for i in range(len(__snake_case ) - pat_len + 1 ): _A = True for j in range(__snake_case ): ...
107
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) ...
6
0
from __future__ import annotations import string from itertools import cycle, product from pathlib import Path __a: str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) __a: list[int] = [ord(letter) for letter in string.ascii_lowercase] __a: ...
108
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class Up...
6
0
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithP...
109
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""P...
6
0
"""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 vocab first, and then a tiny model - so the outcome is truly tiny - # all files...
110
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safet...
6
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __a: int = logging.get_logger(__name__) __a: int = { """google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""", # See all PEGASUS models at h...
152
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""...
6
0
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICE...
581
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelC...
6
0
import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowerCamelCase__ = logging.get_logger(__name__) class _lowerCAmelCase ( UpperCamel...
381
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailabl...
6
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, XLMRoberta...
608
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamel...
6
0
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBloc...
179
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Enco...
6
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Dict =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Any ={ '''facebook/vit-mae-base''': '''https://huggingface.co/facebook/vit-mae-base/resolve/main/config.j...
428
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_byte...
6
0
'''simple docstring''' 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 f...
229
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function:...
6
0
'''simple docstring''' import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForCon...
697
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, SwinConfig from transformers.utils import logg...
6
0
"""simple docstring""" from torch import nn class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : List[Any] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[Any]): """simple docstring""" super().__in...
567
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCa...
6
0
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowerCamelCase : int = logging.get_logger(__name__) class _UpperCamelCase : def __init__...
367
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 AcceleratorState from accelerate.test_util...
6
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py a__ : Any = "...
165
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutp...
6
0
'''simple docstring''' import os def __UpperCamelCase ( ): with open(os.path.dirname(UpperCamelCase__ ) + '''/p022_names.txt''' ) as file: lowercase__ : int = str(file.readlines()[0] ) lowercase__ : Optional[Any] = names.replace('''\"''' , '''''' ).split(...
152
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor...
6
0
"""simple docstring""" from __future__ import annotations from random import random from typing import Generic, TypeVar lowercase__ = TypeVar("KT") lowercase__ = TypeVar("VT") class SCREAMING_SNAKE_CASE__ ( Generic[KT, VT] ): def __init__(self , _lowerca...
581
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import R...
6
0
def lowercase_ ( SCREAMING_SNAKE_CASE : int = 60_08_51_47_51_43 ): """simple docstring""" try: snake_case__ : Optional[int] =int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: ...
381
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCame...
6
0
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black __lowerCamelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 ...
608
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for...
6
0
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionM...
179
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import d...
6
0
def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) lowercase = str(bin(UpperCamelCase__ ) )[2:] # remove the leading "0b" lowercase = str(bin(UpperCamelCase__ ) ...
428
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = ...
6
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCAmelCase = { """configur...
229
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we ...
6
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, DistilB...
697
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) ...
6
0
"""simple docstring""" def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: '''simple docstring''' return [sentence[i : i + ngram_size] for i in range(len(UpperCamelCase__ ) - ngram_size + 1 )] if __name__ == "__main__": ...
567
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class Up...
6
0
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 DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_ver...
367
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""P...
6
0
def snake_case (UpperCamelCase : float , UpperCamelCase : list[float] ): '''simple docstring''' if discount_rate < 0: raise ValueError("""Discount rate cannot be negative""" ) if not cash_flows: raise ValueError("""Cash flows list cannot be empty""" )...
165
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safet...
6
0
'''simple docstring''' import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_ava...
152
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""...
6
0
"""simple docstring""" import sys import turtle def __magic_name__ ( _lowerCamelCase : tuple[float, float] , _lowerCamelCase : tuple[float, float] ): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def __magic_name__ ( _lowerCamelCase :...
581
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelC...
6
0
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel lowerCamelCase__ = False lowerCamelCase__ = True lowerCamelCase__ = False if __name__ == "__main__": ...
381
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailabl...
6
0
"""simple docstring""" class _snake_case : '''simple docstring''' def __init__( self : int , snake_case : list ): UpperCAmelCase_ :Tuple = set_counts UpperCAmelCase_ :Dict = max(__A ) UpperCAmelCase_ :Union[str, An...
608
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamel...
6
0
"""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 = ...
179
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Enco...
6
0
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from...
428
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_byte...
6
0
'''simple docstring''' __lowerCAmelCase = """\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 git+https://github....
229
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function:...
6
0
'''simple docstring''' import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_...
697
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, SwinConfig from transformers.utils import logg...
6
0