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""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...sched...
223
"""simple docstring""" import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration...
223
1
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ......
542
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler...
542
1
"""simple docstring""" from torch import nn def snake_case_ ( A_ : int ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": retu...
83
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A__: Optional[int] = logging.get...
694
0
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( __snake_case : int | str ) -> bool: """simple docstring""" A__ : List[str] =str(__snake_case ) return n == n[::-1] def __lowerCamelCase ( __snake_case : int = 1_000_000 )...
687
'''simple docstring''' 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 __snake_case : List[Any] = logging.get_logger(__name__) class lowerCamelCase ( lowercase_...
687
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvai...
273
"""simple docstring""" def __magic_name__ ( UpperCamelCase : float , UpperCamelCase : float , UpperCamelCase : float , UpperCamelCase : float , UpperCamelCase : float , ) -> float: a__ = [redshift, radiation_density, matter_densit...
273
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings _lowercase : Optional[int] = r""" [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be use...
50
'''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...
50
1
"""simple docstring""" from __future__ import annotations def lowerCamelCase ( _snake_case ): if not nums: return 0 UpperCAmelCase__ : Optional[int] = nums[0] UpperCAmelCase__ : str = 0 for num in nums[1:]: UpperCAmelCase__ , ...
110
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoForme...
110
1
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class snake_case__(Generic[T] ): """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE ...
81
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict ...
81
1
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self , *, ...
242
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowerCAmelCase : Union[str, Any] ...
242
1
'''simple docstring''' from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 snake_case_ : List[str] = { # 1536-bit 5: ...
708
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring"""...
644
0
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTes...
10
'''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...
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _A : Tuple = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swi...
330
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging imp...
330
1
"""simple docstring""" def lowerCamelCase_( _lowerCamelCase ) -> Dict: '''simple docstring''' if not head: return True # split the list to two parts _lowerCamelCase, _lowerCamelCase : List[str] = head.next, head while fast and fast.next: _...
46
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case = { """configuration_bigbird_pegasus""": [ """BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BigBirdPegasusConfig""", ...
178
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase = {"""configuration_vit_msn""": ["""VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMSNConfig"""]} try: if not is_torch_available(): raise OptionalDepend...
207
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def SCREAMING_SNAKE_CASE( ) -> int: a__ : List[str] = { "repo_name": ["test_repo1", "test_repo2", "test_repo3"], "path": ["test_1....
207
1
# Algorithm for the pigeonhole sorting def _SCREAMING_SNAKE_CASE ( lowercase : str ): '''simple docstring''' lowerCamelCase_ = min(lowercase ) # min() finds the minimum value lowerCamelCase_ = max(lowercase ) # max() finds the ...
70
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { '''s-JoL/Open-Llama-V1''': '''https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/c...
502
0
from __future__ import annotations import os from typing import Any import requests __lowerCAmelCase : Any = "https://api.github.com" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user __lowerCAmelCase : Union[str, Any] = B...
715
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 ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_ver...
164
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 model through reduction of a normal pre-trained model, bu...
104
"""simple docstring""" import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMix...
104
1
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# A = [ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0...
46
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available A = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } tr...
46
1
import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets _UpperCamelCase : Optional[Any] ='\\n@inproceedings{snover-etal-2006-study,\n title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n author = "Snover, Matthew and...
206
def a__ (__lowercase :str , __lowercase :str ) -> float: def get_matched_characters(__lowercase :str , __lowercase :str ) -> str: _A : Union[str, Any] = [] _A : Dict = min(len(_stra ) , len(_stra ) ) // 2 ...
206
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
574
'''simple docstring''' from __future__ import annotations from PIL import Image # Define glider example _lowercase : Union[str, Any] =[ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0,...
574
1
'''simple docstring''' class _a : '''simple docstring''' def __init__( self ) -> str: snake_case : Optional[Any] = 0 snake_case : List[str] = 0 snake_case : Union[str, Any] ...
116
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : Optional[int] = { """configuration_pegasus_x""": ["""PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PegasusXCon...
116
1
'''simple docstring''' def __snake_case ( _UpperCAmelCase : int = 100): UpperCamelCase = (n * (n + 1) // 2) ** 2 UpperCamelCase = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F'''{solution() = }''') ...
715
'''simple docstring''' import tensorflow as tf from ...tf_utils import shape_list class lowercase__ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , low...
350
0
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase ( lowercase_): """simple docstring""" def __init__( self : Optional[Any...
404
'''simple docstring''' import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_te...
404
1
'''simple docstring''' def SCREAMING_SNAKE_CASE ( a_ : Optional[int] , a_ : int ): __a = int(__lowerCAmelCase ) # Initialize Result __a = [] # Traverse through all denomination for denomination in reversed(__lowerCAmelCase ): #...
712
'''simple docstring''' def SCREAMING_SNAKE_CASE ( a_ : int ): __a = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def SCREAMING_SNAKE_CASE ( a_ : int = 100 ): __a = 1 __a = 2 for i ...
490
0
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils ...
63
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffuse...
630
0
from scipy.stats import pearsonr import datasets __UpperCamelCase : Tuple = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumpt...
712
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __UpperCamelCase : Union[str, Any] = { 'configuration_layoutlmv2': ['LAYOUTLMV2_PRETRAIN...
458
0
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> Dict: '''simple docstring''' return ConvertCommand( args.model_type, args.tf_checkpoint, args.pytorch...
343
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClass...
343
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer l...
37
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class _snake_case ( lowercase__): def A__ ( self : Optional[Any], __lowercase : str ): with open(__lowercase, encoding="utf-8" ) as ...
37
1
'''simple docstring''' import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) ...
75
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( ...
599
0
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging lowerCAmelCase : Tuple = logging.get_logger(__name__) def lowerCAmelCase ( UpperCamelCase__ : List[Any] ) -> ...
146
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 a ( __lowercase ): SCREAMING_SNAKE_CASE__ ...
146
1
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, res...
391
"""simple docstring""" from manim import * class __lowerCAmelCase ( UpperCAmelCase ): '''simple docstring''' def UpperCamelCase__ ( self: int ): UpperCamelCase_ =Rectangle(height=0.5 , width=0.5 ) UpperCamelCase_ =Rectangle(...
391
1
'''simple docstring''' import math def _snake_case ( lowercase , lowercase ) -> float: if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of initial intensity if angle < 0 ...
719
'''simple docstring''' __SCREAMING_SNAKE_CASE : int = 9.80_665 def _snake_case ( lowercase , lowercase , lowercase = g ) -> float: if fluid_density <= 0: raise ValueError("""Impossible fluid density""" ) if volume < 0: raise V...
697
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokeniz...
130
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device fro...
130
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.js...
718
"""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 GenerationTesterMixin from ...tes...
544
0
"""simple docstring""" import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_devic...
227
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = OrderedDict( [ # Base mod...
326
0
def __lowercase ( _UpperCAmelCase ) -> bool: '''simple docstring''' return str(lowerCamelCase__ ) == str(lowerCamelCase__ )[::-1] def __lowercase ( _UpperCAmelCase ) -> int: '''simple docstring''' return int(lowerCamelCase__ ) + int(str(lowerCamelCase__ )[::-1]...
710
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class snake_case ( __snake_case ): """simple docstring""" __lowerCAmelCase = (DDIMParallelScheduler,) __lowerCAmelCase = (("""eta""", 0.0), ("""num_inference_steps"""...
576
0
import gc import threading import time import psutil import torch class __a : def __init__( self : Dict ): '''simple docstring''' UpperCamelCase__ : Any = psutil.Process() UpperCamelCase__ : int ...
228
lowerCamelCase : dict[str, float] ={ "km/h": 1.0, "m/s": 3.6, "mph": 1.60_9344, "knot": 1.852, } lowerCamelCase : dict[str, float] ={ "km/h": 1.0, "m/s": 0.2_7777_7778, "mph": 0.6_2137_1192, "knot": 0.5_3995_6803, } de...
228
1
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": _a : Optional[int] = argparse.ArgumentParser( description=( """Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned""" ...
111
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils im...
111
1
'''simple docstring''' # Imports import numpy as np class _snake_case : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ): '''simple docstring''' ...
284
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituT...
132
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_to...
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_to...
71
0
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __UpperCamelCase ( unittest.TestCase ): def a__ ( self :Dict ): snake_case_ : List[str] = get_activation("""swi...
334
'''simple docstring''' __A : List[Any] = { 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f', } def UpperCAmelCase ( lowerCamelCase_ :float ...
334
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ : List[Any] = logging.get_logger(__name__) lowerCAmelCase__ : ...
502
'''simple docstring''' from collections.abc import Generator def _a ( ): """simple docstring""" snake_case__ , snake_case__ : List[Any] = 0, 1 while True: snake_case__ , snake_case__ : str = b, a + b yield b def ...
502
1
import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings snake_case = logging...
67
'''simple docstring''' import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter ...
294
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.ut...
505
"""simple docstring""" def _snake_case ( _snake_case : bytes ) -> str: '''simple docstring''' return "".join([hex(_snake_case )[2:].zfill(2 ).upper() for byte in list(_snake_case )] ) def _snake_case ( _snake_case : ...
505
1
"""simple docstring""" import os from pathlib import Path def lowercase ( ) -> Optional[int]: from torch.utils.cpp_extension import load __magic_name__ = Path(__a ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' __magic_name__ = [ root / filename for filen...
490
'''simple docstring''' import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset __lowerCAmelCase = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (...
229
0
'''simple docstring''' import argparse import math import traceback import dateutil.parser as date_parser import requests def lowerCamelCase__ ( _A ): a : Tuple = {} a : List[Any] = job['started_at'] a : str = job['completed_at'] a : Dict ...
195
'''simple docstring''' import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available()...
195
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """facebook/data2vec-text-base""": """https://huggi...
658
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase ...
84
0
'''simple docstring''' def snake_case_ ( lowercase__ : str ): '''simple docstring''' _lowerCAmelCase =0 for ch in input_str: _lowerCAmelCase =ord(lowercase__ ) _lowerCAmelCase =pow(2 , lowercase__ ) # If we alre...
717
import math def snake_case_ ( lowercase__ : int ): '''simple docstring''' _lowerCAmelCase =[True] * n _lowerCAmelCase =False _lowerCAmelCase =False _lowerCAmelCase =True for i in range(3 , int(n**0.5 + 1 ) , 2 ): ...
149
0
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...
12
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase__ : List[Any] = logging.get_logger(__name__) lowerCamelCase__ : Union[str, Any] = { "...
12
1
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def UpperCamelCase_( __magic_name__ : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" ...
382
from __future__ import annotations from math import pow, sqrt def UpperCamelCase_( __magic_name__ : float , __magic_name__ : float , __magic_name__ : float ): """simple docstring""" if (resistance, reactance, impedance).count(0 ) != 1: ...
382
1
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() a = logging.get_logger(__name__)...
7
"""simple docstring""" import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_...
607
0
from __future__ import annotations def UpperCamelCase__ ( UpperCAmelCase ) -> Optional[int]: """simple docstring""" return len(set(UpperCAmelCase ) ) == len(UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
718
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 from ..image_util...
307
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_av...
476
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : Optional[int] = logging.get_logger(__name__) __lowercase : str = { 'google/pix2struct-textcaps-base': ( 'ht...
476
1
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): return 10 - x * x def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): # Bolzano theory in order to find if there is a root between a and b if equation(SCREAMING_SNAKE...
438
'''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_avai...
438
1
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils...
40
"""simple docstring""" import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ ...
426
0
import comet # From: unbabel-comet import torch import datasets __snake_case = datasets.logging.get_logger(__name__) __snake_case = """\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel's ...
715
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMix...
117
0
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Acceler...
47
import math from datetime import datetime, timedelta def UpperCAmelCase__ ( lowerCamelCase_ : int ): __a : Union[str, Any] = year % 1_9 __a : int = year % 4 __a : Optional[int] = year % 7 __a : Dict...
47
1
from ...processing_utils import ProcessorMixin class UpperCamelCase ( _a ): snake_case_ : int = """SpeechT5FeatureExtractor""" snake_case_ : Tuple = """SpeechT5Tokenizer""" def __init__( self : Any , SCREAMING_SNAKE_CASE : str...
707
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_t...
473
0
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 import torch.nn...
279
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ): """simple docstring""" def lowerCamelCase__ ( self : Any , lowerCAmelCase : str ) -> ...
279
1
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...
701
def lowercase__( A ): return " ".join( ''.join(word[::-1] ) if len(A ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('Hey wollef sroirraw'))
303
0
"""simple docstring""" import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
82
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCamelCase = False class lowercase_...
82
1
'''simple docstring''' from copy import deepcopy class __snake_case : def __init__( self : Any , _UpperCAmelCase : list[int] | None = None , _UpperCAmelCase : int | None = None ) -> None: '''simple docstring''' if arr is None and size i...
704
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_config...
196
0
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipel...
99
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, Wav...
193
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_...
637
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, ...
637
1
# 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 easier to use for tuning thi...
317
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase__ ( __snake_case , __snake_case , __snake_case ) -> str: # Initialise PyTorch mo...
317
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A__ = {"""configuration_fnet""": ["""FNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FNetConfig"""]}...
49
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_av...
49
1
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( 'The converted tokenize...
219
import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class __A( unittest.TestCas...
219
1
'''simple docstring''' import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : str = (IPNDMScheduler,) _lowercas...
162
'''simple docstring''' import numpy as np from transformers import Pipeline def A (__lowerCamelCase :Any ): _lowerCAmelCase = np.max(__lowerCamelCase , axis=-1 , keepdims=__lowerCamelCase ) _lowerCAmelCase = np.exp(outputs - maxes ) return shifted_exp / shifted...
162
1
"""simple docstring""" import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subpro...
177
"""simple docstring""" from math import sqrt def lowerCamelCase_ ( __lowerCAmelCase ) -> bool: '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" ...
530
0
from __future__ import annotations from collections.abc import Callable __lowerCamelCase : int = list[list[float | int]] def A__ ( _a : Matrix , _a : Matrix ): '''simple docstring''' snake_case__ : int =len(_a ) snake_case__ : Mat...
448
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets __lowerCamelCase : Dict = """\ @inproceedings{popovic-2015-chrf, title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\", author = \"Popovi{\'c}, Maja\", booktitle = \"...
448
1
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOut...
558
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets A : Dict = '\\n@inproceedings{popovic-2015-chrf,\n title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation",\n author = "Popovi{\'c}, Maja",\n booktitle = "Proceedin...
15
0
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class __SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): ...
717
'''simple docstring''' import qiskit def _lowerCamelCase ( lowerCamelCase_ : int = 2 ): """simple docstring""" UpperCAmelCase_ : List[Any] = qubits # Using Aer's simulator UpperCAmelCase_ : str = qiskit.Aer.get_backend('aer_simu...
389
0
import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import i...
322
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available UpperCamelCase__ = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyN...
322
1
"""simple docstring""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE...
704
"""simple docstring""" import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput _A = logging.getLogger(__name__) if is_torch_tpu_available(che...
507
0
'''simple docstring''' import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import ...
577
'''simple docstring''' import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate...
577
1
def lowerCAmelCase__ ( a__ ) ->str: '''simple docstring''' return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
701
import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, ...
82
0
'''simple docstring''' from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def UpperCAmelCase ( ): lowerCamelCase : List[str] = { """repo_name""": ["""test_repo1"""...
320
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...
336
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 ...
560
"""simple docstring""" import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def __A (_SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" return np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) class ...
560
1
from __future__ import annotations import typing from collections import Counter def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(A__, max_perimeter ...
101
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from acc...
376
0
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets A_ = datasets.logging.get_logger(__name__) A_ = "\\n@InProceedings{moosavi...
465
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets A_ = datasets.logging.get_logger(__name__) A_ = "\\n@InProceedings{moosavi...
465
1
A : Optional[int] = {} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[int]: # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible...
287
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accele...
180
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class UpperCA...
702
def a ( _UpperCAmelCase : list[int] , _UpperCAmelCase : list[int] ): '''simple docstring''' __UpperCAmelCase : Dict = len(_UpperCAmelCase ) print('''The following activities are selected:''' ) # The first activity is always...
241
0
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a : Any = logging.get_logger(__name__) a : List[str] = { """nielsr/canine-s""": 2_048, } # Unicode defines 1,114,112...
63
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_forma...
423
0
from __future__ import annotations from typing import Any class _lowerCAmelCase : def __init__( self , _UpperCamelCase ) -> None: lowerCAmelCase_ = num_of_nodes lowerCAmelCase_ = [] lowerCAmelCase_ = {} def __a...
709
from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class _lowerCAmelCase ( __a ): _lowercase ='''transfo-xl''' _lo...
279
0
'''simple docstring''' import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class _UpperCamelCase ( A ): '''simple docstring''' def __init__( self : List[Any] , _lowerCAmelCase...
474
'''simple docstring''' import os from collections import deque import torch from torch.utils.data import Dataset class _UpperCamelCase ( A ): '''simple docstring''' def __init__( self : Optional[int] , _lowerCAmelCase : Tuple="" , _lowerCAmelCase : List[str]="train"): ...
474
1
'''simple docstring''' import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational i...
568
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin ...
568
1
from __future__ import annotations import time import numpy as np UpperCamelCase = [8, 5, 9, 7] UpperCamelCase = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCamelCase = [ [3, 2, 1, 4], [0, 2, 5, 2], [5,...
61
# 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 # # Unles...
61
1
import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __lowercase ...
452
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers impor...
452
1
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class a ( lowerCAmelCase_ ): __lowerCAmelCase : Li...
252
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def _lowerCAmelCase ( lowercase ) -> Optional[Any]: # vision encoder if "img_encoder.pos_embed" in name: __lowerCAm...
689
0
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = len(__a ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: SCREAM...
628
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def ...
628
1
import qiskit def a__ ( A__, A__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register SCREAMING_SNAKE_CASE_ : List[str] = qiskit.QuantumCircuit(A_, A_ ...
101
'''simple docstring''' import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from d...
577
0
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , ...
311
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a ni...
311
1
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_doc...
272
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase = { '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlipConfig'...
272
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs ...
647
def __lowerCamelCase (UpperCAmelCase__ : list[int] ): if not numbers: return 0 if not isinstance(UpperCAmelCase__ , (list, tuple) ) or not all( isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for number in numbers ): raise ValueError("numbers...
647
1
from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Dict = logging.get_logger(__name__) A__ : Optional[int] = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class lowercase ( _A ): __a = """c...
233
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
529
0
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def lowerCamelCase_ ( A : Dict , A : List[Any]=() , A : List[Any]=None , A : str="no" , A : Optional[Any]=...
704
def lowerCamelCase_ ( ): """simple docstring""" return [ a * b * (10_00 - a - b) for a in range(1 , 9_99 ) for b in range(A , 9_99 ) if (a * a + b * b == (10_00 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'''{solutio...
413
0
'''simple docstring''' import os __lowerCAmelCase = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 1_00, "D": 5_00, "M": 10_00} def __UpperCamelCase ( lowercase_ : str ): """simple docstring""" a_ = 0 a_ = 0 while in...
536
'''simple docstring''' def __UpperCamelCase ( lowercase_ : list[int] , lowercase_ : list[int] , lowercase_ : int ): """simple docstring""" return not any( neighbour == 1 and colored_vertices[i] == color for i, ne...
536
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 MaskGenera...
65
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_ten...
65
1
def __UpperCAmelCase ( __a : str ) -> list: """simple docstring""" if n_term == "": return [] _a : list = [] for temp in range(int(__a ) ): series.append(F"""1/{temp + 1}""" if series else '''1''' ) retu...
14
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake a__ = numpy.array([0, 0]) a__ = numpy.array([0.5, 0.8660254]) a__ = numpy.array([1, 0]) a__ = [VECTOR_1, VEC...
14
1
'''simple docstring''' import operator as op def SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE ): lowerCAmelCase_ : Union[str, Any] =[] lowerCAmelCase_ : Tuple =lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int(x / y ) ...
305
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor __lowercase = logging.get_logger(__name__) class _snake_case ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str...
305
1