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
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) a = { 'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'S...
412
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline a = logging.get_logger(__name__) @add_end_docstring...
412
1
'''simple docstring''' import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __snake_case = { """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/...
603
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_d...
603
1
"""simple docstring""" import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a = logging.get_logger(__name__) a = {'''vocab_file''': '''vocab.txt'''...
7
'''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, resize, ...
507
0
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('''repo_id''' , ['''canonical_dataset_name''', '''org-name/dataset-name'''] ) @pytest.mark.parametrize('''path''' , ['''filename.csv''', '''filename with blanks.csv'''] ...
701
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _UpperCAmelCase : List[str] = { "configuration_electra": ["ELECTRA_PRETRAINED_CONFIG_A...
288
0
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, TFBase...
352
import requests _lowerCamelCase : int = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=""" def __a ( __lowerCAmelCase ) -> None: # fetching a list of articles in json format SCREAMING_SNAKE_CASE : List[str] = requests.g...
352
1
def _a ( lowerCamelCase__ ) -> list: if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence lowerCamelCase_ : int = gray_code_sequence_string(__A ) # # convert them to integers for i in rang...
708
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX models at https:...
144
0
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants SCREAMING_SNAKE_CASE : Dict = Mapping[str, np.ndarray] SCREAMING_SNAKE_CASE : int = Mapping[str, Any] #...
635
import numpy as np import datasets SCREAMING_SNAKE_CASE : Optional[int] = "\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt ...
635
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices Uppe...
716
"""simple docstring""" def __lowercase ( a : str , a : str ) -> str: __snake_case : int =len(a ) __snake_case : int =len(a ) __snake_case : int =( first_str_length if first_str_length > second_str_length else sec...
497
0
UpperCamelCase__ = 'Input must be a string of 8 numbers plus letter' UpperCamelCase__ = 'TRWAGMYFPDXBNJZSQVHLCKE' def UpperCamelCase__ ( UpperCAmelCase_ ) -> bool: '''simple docstring''' if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ...
322
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_...
322
1
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''huggingface/time-series-transformer-tourism-monthly''': ( '''...
494
"""simple docstring""" import sys lowerCAmelCase_ = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' ...
494
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import ...
19
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( snake_case__ :int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples ...
67
0
'''simple docstring''' import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.u...
609
'''simple docstring''' def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase : Optional[Any] = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): UpperCAmelCase : List...
609
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONF...
589
"""simple docstring""" import numpy as np def A__ ( __lowerCamelCase ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
589
1
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _UpperCamelCase ( ): lowercase_ : str = ArgumentParser( description=( ...
438
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): # preprocessing the first row for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column ...
438
1
import warnings from functools import wraps from typing import Callable def __SCREAMING_SNAKE_CASE ( a__ : Callable ) -> Callable: @wraps(a__ ) def _inner_fn(*a__ : Union[str, Any] ,**a__ : Any ): warnings.warn( (f"""'{fn.__name__}' is experimental and...
17
from __future__ import annotations import math def _a ( lowerCAmelCase )-> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes ...
360
0
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {"vocab_file": "vocab.json"} SCREAMING_SNAKE_CASE__ = { "vocab_file":...
718
def lowercase ( a ): '''simple docstring''' SCREAMING_SNAKE_CASE_ :set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack SCREAMING_SNAKE_CASE_ :set[int] = set() return any( node not in visited and depth_f...
140
0
'''simple docstring''' from __future__ import annotations import string from itertools import cycle, product from pathlib import Path SCREAMING_SNAKE_CASE = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) SCREAMING_SNAKE_CASE = [ord(letter) for let...
94
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( snake_case : list )-> list: '''simple docstring''' UpperCAmelCase__ : List[str] = False while is_sorted is False: # Until all the indices are traversed keep looping UpperCAmelCase__ ...
438
0
from dataclasses import dataclass from typing import Dict, 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 .attention_processor import AttentionProcessor, AttnProcessor from .modeli...
334
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 ) __A : Optional[Any] = logging.getLogger(__name__) if __name__ == "__main__": __A : int...
334
1
"""simple docstring""" def _SCREAMING_SNAKE_CASE (): return [list(range(1000 - i , -1000 - i , -1 ) ) for i in range(1000 )] __UpperCamelCase : Union[str, Any] = generate_large_matrix() __UpperCamelCase : Tuple = ( [[4, 3, 2, -1], [3, 2, 1, -1...
4
import sys def __magic_name__ ( __lowerCAmelCase : str ) -> Union[str, Any]: __lowerCamelCase = len(__lowerCAmelCase ) __lowerCamelCase = [[0 for x in range(__lowerCAmelCase )] for x in range(__lowerCAmelCase )] __lowerCamelCase = ...
298
0
"""simple docstring""" a : Union[str, Any] = 8.3_14_45_98 def _UpperCamelCase ( _A , _A ) -> float: """simple docstring""" if temperature < 0: raise Exception("""Temperature cannot be less than 0 K""" ) if molar_mass <= 0: raise Exception("...
19
"""simple docstring""" import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patc...
19
1
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) def __lowerCamelCase (UpperCAmelCase__ ...
403
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_dif...
403
1
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class UpperCAmelCase_ : """simple docstring""" lowerCamelCase : Optional[Union[str, Path]] = None lowerCamelCase : bool = False lowerCamelCase : ...
382
import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusi...
382
1
'''simple docstring''' from dataclasses import dataclass from typing import Dict, 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 .attention_processor import AttentionProcessor, Attn...
370
'''simple docstring''' import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils impo...
370
1
'''simple docstring''' def a__ ( lowerCAmelCase__ ) -> bool: UpperCAmelCase__ : Union[str, Any] = 0 for ch in input_str: UpperCAmelCase__ : Optional[Any] = ord(lowerCAmelCase__ ) UpperCAmelCase__ : List[str] = pow(2...
312
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/config.json''', '...
312
1
'''simple docstring''' import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def A__ ( A_ ) -> Optional[int]: _lowercase = int(A_ ) _lowercase , ...
497
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import versio...
497
1
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import Conf...
207
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basi...
207
1
import argparse import os import re import packaging.version _lowerCamelCase = 'examples/' _lowerCamelCase = { 'examples': (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), 'init': (re.compile(r'^__version__\s+=\s+"([^"...
144
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ...
144
1
def _UpperCamelCase ( UpperCamelCase_ : str ) -> list: """simple docstring""" return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(UpperCamelCase_ ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__("""doctes...
717
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 ( is_pipeline_test, ...
365
0
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class a ( unittest.TestCase ): '''simple docstring''' ...
144
import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device ...
144
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_...
605
'''simple docstring''' import math from numpy import inf from scipy.integrate import quad def snake_case__ ( _A: float ) -> float: '''simple docstring''' if num <= 0: raise ValueError("""math domain error""" ) return quad(_A , 0 , _A , args=(_A...
605
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_a...
56
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_...
239
0
'''simple docstring''' from __future__ import annotations import math import random from typing import Any class lowerCAmelCase__ : def __init__( self : str ) -> None: """simple docstring""" lowerCamelCase_ : list[Any] = [] lowerCamelCas...
702
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils i...
418
0
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 fr...
33
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 import D...
33
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, ...
714
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from data...
656
0
def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0 ): """simple docstring""" lowercase__ = length or len(SCREAMING_SNAKE_CASE ) lowercase__ = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: lowercase__ , lowercase__ = l...
43
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW fro...
531
0
import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTo...
46
class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" snake_case_ = name snake_case_ = val def __str__( self ): """simple docstring""" return f"""{self...
46
1
def a_ ( lowerCAmelCase_ : float, lowerCAmelCase_ : float ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "_...
53
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import...
53
1
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase__ ) class _lowercase ( UpperCAmelCase__ ): _UpperCAmelCase = field(default='''language-modeling''', ...
32
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : Optional[int] = { '''configuration_instructblip''': [ '''INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InstructBlipConfig''', '''...
32
1
"""simple docstring""" import os import sys __UpperCAmelCase = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, A...
65
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { "facebook/s2t-small-librispeech-asr": ( "https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config...
155
0
'''simple docstring''' import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB...
331
'''simple docstring''' import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, Ada...
331
1
'''simple docstring''' from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("""socket.socket""" ) @patch("""builtins.open""" ) def _snake_case ( A_ : Union[str, Any] , A_ : Optional[int] ): """simple docstring""" ...
577
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, ...
577
1
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteSche...
688
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class...
688
1
"""simple docstring""" import math import unittest def snake_case_ ( A_ : int ): '''simple docstring''' assert isinstance(A_, A_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 ...
83
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTester...
110
0
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2...
706
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-g...
476
0
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' raise RuntimeError...
486
def lowerCAmelCase_ ( __A, __A ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ = [1] for i in range(2, __A ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" ...
486
1
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_c...
366
"""simple docstring""" import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __A = 4 __A = 3 class _snake_case ( a__ ): pass def lowercase_ ...
366
1
"""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/LICENSE-2.0 # # Unle...
420
"""simple docstring""" import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch ...
420
1
'''simple docstring''' _lowerCamelCase = 9.8_0665 def _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , snake_case_ = g ): if fluid_density <= 0: raise ValueError("""Impossible fluid density""" ) if volume < 0: raise ValueError("""Impossible Object volume""" ...
572
'''simple docstring''' import unittest import numpy as np from datasets import load_dataset 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, ...
572
1
"""simple docstring""" import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @re...
237
"""simple docstring""" import os from collections import deque import torch from torch.utils.data import Dataset class snake_case_ ( a_ ): def __init__( self , a_="" , a_="train" ): assert os.path.isdir(a_ ) a_ : List[Any] = [] ...
237
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } ...
701
'''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/LICENS...
438
0
from __future__ import annotations def lowercase__ ( A_: list[int] , A_: list[int] , A_: list[int] , A_: list[list[str]] , A_: int , ) -> None: """simple docstring""" __UpperCAmelCase =len(A_ ) ...
68
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): @pr...
612
0
'''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...
271
'''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 transform...
271
1
"""simple docstring""" import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='''%(message)s''') def lowercase ( __snake_case : Optional[Any] ): return input_array.reshape((input_arr...
231
'''simple docstring''' import re from filelock import FileLock try: import nltk __A =True except (ImportError, ModuleNotFoundError): __A =False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _UpperCamelC...
407
0
import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_...
716
"""simple docstring""" from __future__ import annotations class _SCREAMING_SNAKE_CASE : def __init__( self , __A=None ) -> Tuple: lowerCAmelCase_ :Optional[int] = data lowerCAmelCase_ :List[Any] = None ...
256
0
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common imp...
208
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast...
693
0
from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_availabl...
421
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _snake_case : Optional[int] = logging.get_logger(__name__) _snake_case : List[...
421
1
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = (UnCLIPScheduler,) def lowerCamelCase__ (self : Union[str, Any] , **_Upper...
15
import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef __UpperCamelCase : List[Any] = ( 'This metric will be removed from the li...
248
0
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowerCamelCase : List[str] = logging.get_logger(__name__...
707
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, ...
684
0
import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class A_ ( UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Option...
67
"""simple docstring""" a : str = range(2, 20 + 1) a : Optional[Any] = [10**k for k in range(ks[-1] + 1)] a : dict[int, dict[int, list[list[int]]]] = {} def lowercase__(A , A , A , A ) ->Any: ...
218
0
from __future__ import annotations def __UpperCamelCase ( lowerCAmelCase__ : int | str ): __a : Any = str(lowerCAmelCase__ ) return n == n[::-1] def __UpperCamelCase ( lowerCAmelCase__ : int = 1_0_0_0_0_0_0 ): __a : A...
326
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 Accelerator from accelerate.test...
326
1
import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available f...
239
'''simple docstring''' def __A ( a_ : list[list[float]] ): lowerCAmelCase : list[list[float]] = [] for data in source_data: for i, el in enumerate(a_ ): if len(a_ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(a_ ...
525
0
"""simple docstring""" import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=log...
194
"""simple docstring""" from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as impo...
194
1
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def UpperCamelCase ( _a ) -> tuple: '''simple d...
257
from typing import Any import numpy as np def UpperCamelCase ( _a ) -> bool: '''simple docstring''' return np.array_equal(_a , matrix.conjugate().T ) def UpperCamelCase ( _a , _a ) -> Any: '''simple docstring...
257
1
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : Optional[int] ...
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
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_speech_to_text":...
205
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM ...
205
1
"""simple docstring""" import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow...
317
"""simple docstring""" import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.f...
317
1
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging f...
618
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ :Any = logging.get_logger(__name__) lowerCAmelCase__ :Union[str, Any] = { '''facebook/xmod-ba...
618
1
"""simple docstring""" # 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 l...
66
"""simple docstring""" import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCA...
66
1
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels __lowerCAmelCase : Optional[int] = object() # For specifying empty leaf dict `{}` __lowerCAmelCase : ...
509
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __lowerCAmelCase = {'configuration_deit': ['DEIT_PRETRAINED_CON...
466
0
'''simple docstring''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging snake_case : Optional[int]...
339
'''simple docstring''' import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() snake_case : Union[str, Any] = logging.get_logger(__name__) snake_case : List[Any] ...
339
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase : Dict = logging.get_logger(__name__) _lowerCamelCase : Tuple = { """YituT...
352
from datetime import datetime import requests def __a ( __lowerCAmelCase ) -> bytes: SCREAMING_SNAKE_CASE : int = 'https://downloadgram.net/wp-json/wppress/video-downloader/video?url=' SCREAMING_SNAKE_CASE : Any = requests.get(base_url +...
352
1
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def lowerCamelCase_ ( lowerCAmelCase: str , lowerCAmelCase: str , **lowerCAmelCase: Tuple )-> str: _snake_case : List[str] = AutoConfig.from_pretrained(lowerCAmelCase , ...
718
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer lowerCAmelCase_ = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} ...
669
0
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __a :Tuple = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Langu...
86
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( snake_case__ :int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples ...
67
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset from utils import logger class lowerCamelCase_ ( snake_case_ ): def __init__( self : Union[str, Any] , lowerCAmelCase__ : str , lowerCAmelCase__ ...
464
'''simple docstring''' from bisect import bisect from itertools import accumulate def UpperCAmelCase ( A : Tuple , A : Optional[Any] , A : Dict , A : Any ): SCREAMING_SNAKE_CASE : List[str] = sorted(zip(A , A ) , key...
464
1
"""simple docstring""" def _UpperCamelCase ( UpperCamelCase = 1 , UpperCamelCase = 1000 ) -> int: """simple docstring""" __UpperCAmelCase : int = 1 __UpperCAmelCase : Tuple = 0 for divide_by_number in range(U...
77
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokeni...
77
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def UpperCAmelCase_ ( __lowercase : int ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = [ """encoder...
715
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipel...
119
0
def __lowerCAmelCase ( _UpperCamelCase ) -> int: '''simple docstring''' return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __lowerCAmelCase ( _UpperCamelCase ) -> bool: '''simple docstring''' lowerCamel...
306
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFMode...
306
1
import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase__( __lowercase , unittest.TestCase ): ...
712
from __future__ import annotations import requests def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(__lowerCamelCase ).json() def lowerCa...
381
0
from ..utils import DummyObject, requires_backends class A__ ( metaclass=snake_case__ ): """simple docstring""" __magic_name__ = ['torch'] def __init__( self , *__snake_case , **__snake_case ): requires_backends(self ...
550
'''simple docstring''' import flax.linen as nn import jax import jax.numpy as jnp class _UpperCAmelCase ( nn.Module ): __lowerCamelCase: int __lowerCamelCase: jnp.dtype = jnp.floataa def lowerCAmelCase__ ( self : Optional[Any] ): ...
620
0
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets UpperCamelCase__ = '''\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex ...
143
import qiskit def UpperCAmelCase__ ( _A , _A ): """simple docstring""" a_ = qiskit.Aer.get_backend('''aer_simulator''' ) a_ = qiskit.QuantumCircuit(4 , 2 ) # encode inputs in qubits 0 and 1 if bita == 1: qc_ha.x(...
143
1
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu...
359
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase : Any = logging.get_logger(__name__) lowerCAmelCase : List[str] = { 'nielsr/canine-s': 20_48, } # Unicode defines 1,114,112 total “codepoints” low...
511
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->str: if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) A__ : str = str(bin(UpperCAmelCase__ ...
498
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->str: if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) A__ : str = str(bin(UpperCAmelCase__ ...
498
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor SCREAMING_SNAKE_CASE__ : int =logging.get_logger(__name__) class _UpperCAmelCase ( a_ ): """simple docstring""" def _...
434
"""simple docstring""" SCREAMING_SNAKE_CASE__ : int =6_5521 def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->int: _lowerCamelCase : Union[str, Any] = 1 _lowerCamelCase : List[str] = 0 for plain_chr in plain_text: _lowerCamelCase : Di...
434
1
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) de...
96
def _A (UpperCamelCase : int , UpperCamelCase : int ) ->int: '''simple docstring''' while b: lowerCamelCase__ ,lowerCamelCase__ : int = b, a % b return a def _A (UpperCamelCase : int , UpperCamelCase : int ) ->...
96
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDepe...
129
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtu...
78
0
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_availab...
465
'''simple docstring''' def A_ ( snake_case = 100 ): SCREAMING_SNAKE_CASE:Dict = 0 SCREAMING_SNAKE_CASE:Optional[int] = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ =...
465
1
"""simple docstring""" import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_incr...
102
def lowerCAmelCase_ (lowerCAmelCase__: Union[str, Any] , lowerCAmelCase__: Optional[int] ): """simple docstring""" UpperCAmelCase_: List[str] = 0 UpperCAmelCase_: Tuple = len(lowerCAmelCase__ ) - 1 while left <= right: # avoid d...
556
0
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : List[str] ...
705
from __future__ import annotations from typing import Any class lowerCamelCase_ : def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 0 ): """simple docstring""" __magic_name__ , __magic_name__ :Any ...
180
0
"""simple docstring""" from collections.abc import Generator def snake_case ( ) -> Generator[int, None, None]: _snake_case , _snake_case = 0, 1 while True: _snake_case , _snake_case = b, a + b yield b def snake_case ( lower...
103
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def __lowerCAmelCase ( __snake_case = "" ): __lowerCAmelCase = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" __lowerCAmelCase = BeautifulSoup(re...
367
0
'''simple docstring''' from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models im...
704
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase : str = logging.get_logger(__name__) # TODO: upload to AWS lowercase : Optional[Any] = { 'yjernite/retribert-base-uncased': ( 'https://...
343
0
"""simple docstring""" import heapq def __magic_name__ ( UpperCamelCase : dict ) -> set[int]: a__ = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq work...
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
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyN...
291
from __future__ import annotations lowerCamelCase__ = list[list[int]] # assigning initial values to the grid lowerCamelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0...
291
1
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class UpperCAmelCase_ ...
76
"""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...
76
1
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipel...
107
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( ...
107
1
def SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ): """simple docstring""" if index == number_of_items: return 0 _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAK...
605
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, ...
605
1
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor UpperCamelCase_ = logging.get_logger(__name__) class a ( __UpperCAmelCase ): def __init__( self : List[Any] , *snake_case__ : Optional[int] , ...
376
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) UpperCamelCase_ = pytest.mark.integration @pytest.mark.parametrize("path" , ["paws", "csv"] ) de...
376
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _snake_case : str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailabl...
693
import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def _A ( __snake_c...
693
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_u...
302
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () lowerCamelCase_ : Union[str, Any] = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by de...
302
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.ut...
421
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function __magic_name__ = 1.054_571_817E-34 # unit of ℏ : J * s __magic_name__ = 3E8 # unit of c : m * s^-1 def __magic_name...
250
0
"""simple docstring""" from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _lowercase ( __UpperCAmelCase ): def __i...
711
"""simple docstring""" from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('socket.socket' ) @patch('builtins.open' ) def UpperCAmelCase ( a_, a_ ): '''simple docstring''' lowerCamelCase : int = Mock() lowerCamelCase ...
133
0