code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
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 import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def __a ( A__ : Any , A__ : Optional[int]=False ): try: SCREAMING_SNAKE_CASE = os.environ[key] except KeyError: # KEY isn't set, default to `default`. SCREAMING_SNAKE_CASE = default else: # KEY is set, convert it to True or False. try: SCREAMING_SNAKE_CASE = strtobool(lowerCAmelCase_ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"If set, {key} must be yes or no." ) return _value __A : str = parse_flag_from_env('RUN_SLOW', default=False) __A : List[Any] = parse_flag_from_env('RUN_REMOTE', default=False) __A : Any = parse_flag_from_env('RUN_LOCAL', default=True) __A : List[str] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression __A : List[str] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') __A : Dict = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') __A : Union[str, Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio __A : Any = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam __A : str = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility __A : List[Any] = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows __A : List[str] = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def __a ( A__ : Tuple ): try: import faiss # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip("test requires faiss" )(lowerCAmelCase_ ) return test_case def __a ( A__ : List[Any] ): try: import regex # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip("test requires regex" )(lowerCAmelCase_ ) return test_case def __a ( A__ : str ): try: import elasticsearch # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip("test requires elasticsearch" )(lowerCAmelCase_ ) return test_case def __a ( A__ : str ): try: import sqlalchemy # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip("test requires sqlalchemy" )(lowerCAmelCase_ ) return test_case def __a ( A__ : Union[str, Any] ): if not config.TORCH_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip("test requires PyTorch" )(lowerCAmelCase_ ) return test_case def __a ( A__ : List[str] ): if not config.TF_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip("test requires TensorFlow" )(lowerCAmelCase_ ) return test_case def __a ( A__ : List[str] ): if not config.JAX_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip("test requires JAX" )(lowerCAmelCase_ ) return test_case def __a ( A__ : Dict ): if not config.PIL_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip("test requires Pillow" )(lowerCAmelCase_ ) return test_case def __a ( A__ : Tuple ): try: import transformers # noqa F401 except ImportError: return unittest.skip("test requires transformers" )(lowerCAmelCase_ ) else: return test_case def __a ( A__ : Optional[Any] ): try: import tiktoken # noqa F401 except ImportError: return unittest.skip("test requires tiktoken" )(lowerCAmelCase_ ) else: return test_case def __a ( A__ : List[str] ): try: import spacy # noqa F401 except ImportError: return unittest.skip("test requires spacy" )(lowerCAmelCase_ ) else: return test_case def __a ( A__ : Optional[int] ): def _require_spacy_model(A__ : List[Any] ): try: import spacy # noqa F401 spacy.load(lowerCAmelCase_ ) except ImportError: return unittest.skip("test requires spacy" )(lowerCAmelCase_ ) except OSError: return unittest.skip("test requires spacy model '{}'".format(lowerCAmelCase_ ) )(lowerCAmelCase_ ) else: return test_case return _require_spacy_model def __a ( A__ : Union[str, Any] ): try: import pyspark # noqa F401 except ImportError: return unittest.skip("test requires pyspark" )(lowerCAmelCase_ ) else: return test_case def __a ( A__ : Optional[Any] ): try: import joblibspark # noqa F401 except ImportError: return unittest.skip("test requires joblibspark" )(lowerCAmelCase_ ) else: return test_case def __a ( A__ : Optional[int] ): if not _run_slow_tests or _run_slow_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip("test is slow" )(lowerCAmelCase_ ) return test_case def __a ( A__ : Optional[int] ): if not _run_local_tests or _run_local_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip("test is local" )(lowerCAmelCase_ ) return test_case def __a ( A__ : str ): if not _run_packaged_tests or _run_packaged_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip("test is packaged" )(lowerCAmelCase_ ) return test_case def __a ( A__ : Tuple ): if not _run_remote_tests or _run_remote_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip("test requires remote" )(lowerCAmelCase_ ) return test_case def __a ( *A__ : Any ): def decorate(cls : Dict ): for name, fn in cls.__dict__.items(): if callable(lowerCAmelCase_ ) and name.startswith("test" ): for decorator in decorators: SCREAMING_SNAKE_CASE = decorator(lowerCAmelCase_ ) setattr(cls , lowerCAmelCase_ , lowerCAmelCase_ ) return cls return decorate class _SCREAMING_SNAKE_CASE ( __lowerCamelCase ): '''simple docstring''' pass class _SCREAMING_SNAKE_CASE ( __lowerCamelCase ): '''simple docstring''' lowerCamelCase__ = 0 lowerCamelCase__ = 1 lowerCamelCase__ = 2 @contextmanager def __a ( A__ : Tuple=OfflineSimulationMode.CONNECTION_FAILS , A__ : Any=1E-1_6 ): SCREAMING_SNAKE_CASE = requests.Session().request def timeout_request(A__ : str , A__ : List[str] , A__ : str , **A__ : Union[str, Any] ): # Change the url to an invalid url so that the connection hangs SCREAMING_SNAKE_CASE = "https://10.255.255.1" if kwargs.get("timeout" ) is None: raise RequestWouldHangIndefinitelyError( F"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) SCREAMING_SNAKE_CASE = timeout try: return online_request(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier SCREAMING_SNAKE_CASE = url SCREAMING_SNAKE_CASE = e.args[0] SCREAMING_SNAKE_CASE = (max_retry_error.args[0].replace("10.255.255.1" , F"OfflineMock[{url}]" ),) SCREAMING_SNAKE_CASE = (max_retry_error,) raise def raise_connection_error(A__ : List[Any] , A__ : List[Any] , **A__ : str ): raise requests.ConnectionError("Offline mode is enabled." , request=lowerCAmelCase_ ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("requests.Session.send" , lowerCAmelCase_ ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("requests.Session.request" , lowerCAmelCase_ ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("datasets.config.HF_DATASETS_OFFLINE" , lowerCAmelCase_ ): yield else: raise ValueError("Please use a value from the OfflineSimulationMode enum." ) @contextmanager def __a ( *A__ : Union[str, Any] , **A__ : Tuple ): SCREAMING_SNAKE_CASE = str(Path().resolve() ) with tempfile.TemporaryDirectory(*lowerCAmelCase_ , **lowerCAmelCase_ ) as tmp_dir: try: os.chdir(lowerCAmelCase_ ) yield finally: os.chdir(lowerCAmelCase_ ) @contextmanager def __a ( ): import gc gc.collect() SCREAMING_SNAKE_CASE = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def __a ( ): import gc gc.collect() SCREAMING_SNAKE_CASE = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def __a ( A__ : List[str] , A__ : List[Any] ): return deepcopy(lowerCAmelCase_ ).integers(0 , 100 , 10 ).tolist() == deepcopy(lowerCAmelCase_ ).integers(0 , 100 , 10 ).tolist() def __a ( A__ : List[str] ): import decorator from requests.exceptions import HTTPError def _wrapper(A__ : Dict , *A__ : List[Any] , **A__ : Union[str, Any] ): try: return func(*lowerCAmelCase_ , **lowerCAmelCase_ ) except HTTPError as err: if str(lowerCAmelCase_ ).startswith("500" ) or str(lowerCAmelCase_ ).startswith("502" ): pytest.xfail(str(lowerCAmelCase_ ) ) raise err return decorator.decorator(_wrapper , lowerCAmelCase_ ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = returncode SCREAMING_SNAKE_CASE = stdout SCREAMING_SNAKE_CASE = stderr async def __a ( A__ : List[Any] , A__ : Tuple ): while True: SCREAMING_SNAKE_CASE = await stream.readline() if line: callback(lowerCAmelCase_ ) else: break async def __a ( A__ : Any , A__ : Any=None , A__ : Optional[int]=None , A__ : List[str]=None , A__ : Any=False , A__ : List[Any]=False ): if echo: print("\nRunning: " , " ".join(lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=lowerCAmelCase_ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCAmelCase_ , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] def tee(A__ : str , A__ : Any , A__ : Tuple , A__ : Tuple="" ): SCREAMING_SNAKE_CASE = line.decode("utf-8" ).rstrip() sink.append(lowerCAmelCase_ ) if not quiet: print(lowerCAmelCase_ , lowerCAmelCase_ , file=lowerCAmelCase_ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout , lambda A__ : tee(lowerCAmelCase_ , lowerCAmelCase_ , sys.stdout , label="stdout:" ) ), _read_stream(p.stderr , lambda A__ : tee(lowerCAmelCase_ , lowerCAmelCase_ , sys.stderr , label="stderr:" ) ), ] , timeout=lowerCAmelCase_ , ) return _RunOutput(await p.wait() , lowerCAmelCase_ , lowerCAmelCase_ ) def __a ( A__ : Optional[Any] , A__ : List[str]=None , A__ : List[Any]=None , A__ : Union[str, Any]=180 , A__ : str=False , A__ : Optional[int]=True ): SCREAMING_SNAKE_CASE = asyncio.get_event_loop() SCREAMING_SNAKE_CASE = loop.run_until_complete( _stream_subprocess(lowerCAmelCase_ , env=lowerCAmelCase_ , stdin=lowerCAmelCase_ , timeout=lowerCAmelCase_ , quiet=lowerCAmelCase_ , echo=lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE = " ".join(lowerCAmelCase_ ) if result.returncode > 0: SCREAMING_SNAKE_CASE = "\n".join(result.stderr ) raise RuntimeError( F"'{cmd_str}' failed with returncode {result.returncode}\n\n" F"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(F"'{cmd_str}' produced no output." ) return result def __a ( ): SCREAMING_SNAKE_CASE = os.environ.get("PYTEST_XDIST_WORKER" , "gw0" ) SCREAMING_SNAKE_CASE = re.sub(R"^gw" , "" , lowerCAmelCase_ , 0 , re.M ) return int(lowerCAmelCase_ ) def __a ( ): SCREAMING_SNAKE_CASE = 29500 SCREAMING_SNAKE_CASE = pytest_xdist_worker_id() return port + uniq_delta
707
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @slow @require_torch def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("bert-base-uncased" ) SCREAMING_SNAKE_CASE = bertabert.config.encoder.vocab_size SCREAMING_SNAKE_CASE = tokenizer.sep_token_id SCREAMING_SNAKE_CASE = tokenizer.cls_token_id SCREAMING_SNAKE_CASE = 128 SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) SCREAMING_SNAKE_CASE = train_dataset.select(range(32 ) ) SCREAMING_SNAKE_CASE = val_dataset.select(range(16 ) ) SCREAMING_SNAKE_CASE = 4 def _map_to_encoder_decoder_inputs(__lowerCamelCase : str ): # Tokenizer will automatically set [BOS] <text> [EOS] SCREAMING_SNAKE_CASE = tokenizer(batch["article"] , padding="max_length" , truncation=__lowerCamelCase , max_length=512 ) SCREAMING_SNAKE_CASE = tokenizer(batch["highlights"] , padding="max_length" , truncation=__lowerCamelCase , max_length=128 ) SCREAMING_SNAKE_CASE = inputs.input_ids SCREAMING_SNAKE_CASE = inputs.attention_mask SCREAMING_SNAKE_CASE = outputs.input_ids SCREAMING_SNAKE_CASE = outputs.input_ids.copy() SCREAMING_SNAKE_CASE = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] SCREAMING_SNAKE_CASE = outputs.attention_mask assert all(len(__lowerCamelCase ) == 512 for x in inputs.input_ids ) assert all(len(__lowerCamelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(__lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = pred.label_ids SCREAMING_SNAKE_CASE = pred.predictions # all unnecessary tokens are removed SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = sum([int(pred_str[i] == label_str[i] ) for i in range(len(__lowerCamelCase ) )] ) / len(__lowerCamelCase ) return {"accuracy": accuracy} # map train dataset SCREAMING_SNAKE_CASE = train_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset SCREAMING_SNAKE_CASE = val_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE = SeqaSeqTrainingArguments( output_dir=__lowerCamelCase , per_device_train_batch_size=__lowerCamelCase , per_device_eval_batch_size=__lowerCamelCase , predict_with_generate=__lowerCamelCase , evaluation_strategy="steps" , do_train=__lowerCamelCase , do_eval=__lowerCamelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer SCREAMING_SNAKE_CASE = SeqaSeqTrainer( model=__lowerCamelCase , args=__lowerCamelCase , compute_metrics=_compute_metrics , train_dataset=__lowerCamelCase , eval_dataset=__lowerCamelCase , tokenizer=__lowerCamelCase , ) # start training trainer.train()
698
0
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() __A : Any = logging.get_logger('transformers.models.speecht5') def __a ( A__ : Tuple , A__ : Dict , A__ : List[Any] ): hf_model.apply_weight_norm() SCREAMING_SNAKE_CASE = checkpoint["input_conv.weight_g"] SCREAMING_SNAKE_CASE = checkpoint["input_conv.weight_v"] SCREAMING_SNAKE_CASE = checkpoint["input_conv.bias"] for i in range(len(config.upsample_rates ) ): SCREAMING_SNAKE_CASE = checkpoint[F"upsamples.{i}.1.weight_g"] SCREAMING_SNAKE_CASE = checkpoint[F"upsamples.{i}.1.weight_v"] SCREAMING_SNAKE_CASE = checkpoint[F"upsamples.{i}.1.bias"] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): SCREAMING_SNAKE_CASE = checkpoint[F"blocks.{i}.convs1.{j}.1.weight_g"] SCREAMING_SNAKE_CASE = checkpoint[F"blocks.{i}.convs1.{j}.1.weight_v"] SCREAMING_SNAKE_CASE = checkpoint[F"blocks.{i}.convs1.{j}.1.bias"] SCREAMING_SNAKE_CASE = checkpoint[F"blocks.{i}.convs2.{j}.1.weight_g"] SCREAMING_SNAKE_CASE = checkpoint[F"blocks.{i}.convs2.{j}.1.weight_v"] SCREAMING_SNAKE_CASE = checkpoint[F"blocks.{i}.convs2.{j}.1.bias"] SCREAMING_SNAKE_CASE = checkpoint["output_conv.1.weight_g"] SCREAMING_SNAKE_CASE = checkpoint["output_conv.1.weight_v"] SCREAMING_SNAKE_CASE = checkpoint["output_conv.1.bias"] hf_model.remove_weight_norm() @torch.no_grad() def __a ( A__ : Optional[Any] , A__ : int , A__ : Tuple , A__ : Optional[int]=None , A__ : List[Any]=None , ): if config_path is not None: SCREAMING_SNAKE_CASE = SpeechTaHifiGanConfig.from_pretrained(_snake_case ) else: SCREAMING_SNAKE_CASE = SpeechTaHifiGanConfig() SCREAMING_SNAKE_CASE = SpeechTaHifiGan(_snake_case ) SCREAMING_SNAKE_CASE = torch.load(_snake_case ) load_weights(orig_checkpoint["model"]["generator"] , _snake_case , _snake_case ) SCREAMING_SNAKE_CASE = np.load(_snake_case ) SCREAMING_SNAKE_CASE = stats[0].reshape(-1 ) SCREAMING_SNAKE_CASE = stats[1].reshape(-1 ) SCREAMING_SNAKE_CASE = torch.from_numpy(_snake_case ).float() SCREAMING_SNAKE_CASE = torch.from_numpy(_snake_case ).float() model.save_pretrained(_snake_case ) if repo_id: print("Pushing to the hub..." ) model.push_to_hub(_snake_case ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) __A : Optional[Any] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
708
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, 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 ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , "num_attention_heads" ) ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : Optional[int]=64 , __lowerCamelCase : Dict=3 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : int=2 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Tuple=[128, 256, 384] , __lowerCamelCase : int=[4, 6, 8] , __lowerCamelCase : Tuple=[2, 3, 4] , __lowerCamelCase : List[str]=[16, 16, 16] , __lowerCamelCase : int=0 , __lowerCamelCase : List[Any]=[2, 2, 2] , __lowerCamelCase : List[str]=[2, 2, 2] , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=True , __lowerCamelCase : int=2 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = kernel_size SCREAMING_SNAKE_CASE = stride SCREAMING_SNAKE_CASE = padding SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = [ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[str] ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = LevitModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) SCREAMING_SNAKE_CASE = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def _snake_case ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = LevitForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) lowerCamelCase__ = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = LevitModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : Any ): return @unittest.skip(reason="Levit does not use inputs_embeds" ) def _snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason="Levit does not support input and output embeddings" ) def _snake_case ( self : Tuple ): pass @unittest.skip(reason="Levit does not output attentions" ) def _snake_case ( self : Tuple ): pass def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : List[Any] ): def check_hidden_states_output(__lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = len(self.model_tester.depths ) + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) SCREAMING_SNAKE_CASE = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : int ): pass def _snake_case ( self : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : int=False ): SCREAMING_SNAKE_CASE = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def _snake_case ( self : List[Any] ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(__lowerCamelCase ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(__lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.gradient_checkpointing_enable() model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(__lowerCamelCase ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}" ): SCREAMING_SNAKE_CASE = problem_type["title"] SCREAMING_SNAKE_CASE = problem_type["num_labels"] SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) SCREAMING_SNAKE_CASE = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=__lowerCamelCase ) as warning_list: SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def _snake_case ( self : List[Any] ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = LevitModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Dict ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([1.0_448, -0.3_745, -1.8_317] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
698
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase__ = "yolos" def __init__( self : Any , __lowerCamelCase : Tuple=768 , __lowerCamelCase : Optional[int]=12 , __lowerCamelCase : Tuple=12 , __lowerCamelCase : Dict=3072 , __lowerCamelCase : Union[str, Any]="gelu" , __lowerCamelCase : Tuple=0.0 , __lowerCamelCase : Optional[Any]=0.0 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Union[str, Any]=1e-12 , __lowerCamelCase : List[Any]=[512, 864] , __lowerCamelCase : Union[str, Any]=16 , __lowerCamelCase : Any=3 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : List[str]=100 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Dict=False , __lowerCamelCase : Any=1 , __lowerCamelCase : Any=5 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : List[Any]=5 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : Union[str, Any]=0.1 , **__lowerCamelCase : Dict , ): super().__init__(**_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = num_detection_tokens SCREAMING_SNAKE_CASE = use_mid_position_embeddings SCREAMING_SNAKE_CASE = auxiliary_loss # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase__ = version.parse("1.11" ) @property def _snake_case ( self : List[str] ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _snake_case ( self : Dict ): return 1e-4 @property def _snake_case ( self : str ): return 12
709
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): return None class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : int ): return None class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = [ # (model_name, model_kwargs) ("bert-base-cased", {}), ("gpt2", {"use_cache": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : Optional[int] ): from transformers import BertModel SCREAMING_SNAKE_CASE = ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"] with NamedTemporaryFile(mode="w+t" ) as vocab_file: vocab_file.write("\n".join(__lowerCamelCase ) ) vocab_file.flush() SCREAMING_SNAKE_CASE = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: SCREAMING_SNAKE_CASE = BertModel(BertConfig(vocab_size=len(__lowerCamelCase ) ) ) model.save_pretrained(__lowerCamelCase ) self._test_export(__lowerCamelCase , "pt" , 12 , __lowerCamelCase ) @require_tf @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(Path(__lowerCamelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) @require_torch @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(__lowerCamelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) def _snake_case ( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Tuple=None , **__lowerCamelCase : List[str] ): try: # Compute path with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE = Path(__lowerCamelCase ).joinpath("model.onnx" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) return path except Exception as e: self.fail(__lowerCamelCase ) @require_torch @require_tokenizers @slow def _snake_case ( self : Dict ): from transformers import BertModel SCREAMING_SNAKE_CASE = BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "pt" ) @require_tf @require_tokenizers @slow def _snake_case ( self : int ): from transformers import TFBertModel SCREAMING_SNAKE_CASE = TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "tf" ) def _snake_case ( self : int , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = FeatureExtractionPipeline(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = infer_shapes(__lowerCamelCase , __lowerCamelCase ) # Assert all variables are present self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __lowerCamelCase ) self.assertSequenceEqual(variable_names[3:] , __lowerCamelCase ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: "batch", 1: "sequence"} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["output_0"] , {0: "batch", 1: "sequence"} ) self.assertDictEqual(shapes["output_1"] , {0: "batch"} ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask", "token_type_ids"] SCREAMING_SNAKE_CASE = {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__lowerCamelCase ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__lowerCamelCase ) , set(__lowerCamelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__lowerCamelCase , (tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncNonContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__lowerCamelCase ) , 1 ) self.assertEqual(len(__lowerCamelCase ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["input_ids"] ) self.assertEqual(ordered_input_names[0] , "input_ids" ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = generate_identified_filename(Path("/home/something/my_fake_model.onnx" ) , "-test" ) self.assertEqual("/home/something/my_fake_model-test.onnx" , generated.as_posix() )
698
0
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __A : str = logging.get_logger(__name__) def __a ( A__ : Any ): SCREAMING_SNAKE_CASE = MobileNetVaConfig(layer_norm_eps=0.0_0_1 ) if "_quant" in model_name: raise ValueError("Quantized models are not supported." ) SCREAMING_SNAKE_CASE = re.match(R"^mobilenet_v1_([^_]*)_([^_]*)$" , A_ ) if matches: SCREAMING_SNAKE_CASE = float(matches[1] ) SCREAMING_SNAKE_CASE = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". SCREAMING_SNAKE_CASE = 1001 SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE = "huggingface/label-files" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(A_ , A_ , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE = {int(A_ ) + 1: v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = "background" SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def __a ( ): SCREAMING_SNAKE_CASE = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE = Image.open(requests.get(A_ , stream=A_ ).raw ) return im @torch.no_grad() def __a ( A__ : str , A__ : List[str] , A__ : Dict , A__ : Optional[int]=False ): SCREAMING_SNAKE_CASE = get_mobilenet_va_config(A_ ) # Load 🤗 model SCREAMING_SNAKE_CASE = MobileNetVaForImageClassification(A_ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(A_ , A_ , A_ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor SCREAMING_SNAKE_CASE = MobileNetVaImageProcessor( crop_size={"width": config.image_size, "height": config.image_size} , size={"shortest_edge": config.image_size + 32} , ) SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE = model(**A_ ) SCREAMING_SNAKE_CASE = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": SCREAMING_SNAKE_CASE = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ) elif model_name == "mobilenet_v1_0.75_192": SCREAMING_SNAKE_CASE = torch.tensor([-3.9_4_4_0, -2.3_1_4_1, -0.3_3_3_3] ) else: SCREAMING_SNAKE_CASE = None if expected_logits is not None: assert torch.allclose(logits[0, :3] , A_ , atol=1E-4 ) Path(A_ ).mkdir(exist_ok=A_ ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(A_ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(A_ ) if push_to_hub: print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE = "google/" + model_name image_processor.push_to_hub(A_ ) model.push_to_hub(A_ ) if __name__ == "__main__": __A : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __A : str = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
710
from manim import * class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("CPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("GPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Model" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): rect.set_stroke(__lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__lowerCamelCase , buff=0.0 ) self.add(__lowerCamelCase ) cpu_targs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Loaded Checkpoint" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , aligned_edge=__lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) SCREAMING_SNAKE_CASE = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = MarkupText( f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(__lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) SCREAMING_SNAKE_CASE = MarkupText( f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__lowerCamelCase ) , Write(__lowerCamelCase ) ) self.play(Write(__lowerCamelCase , run_time=1 ) , Create(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): SCREAMING_SNAKE_CASE = fill.copy().set_fill(__lowerCamelCase , opacity=0.7 ) target.move_to(__lowerCamelCase ) first_animations.append(GrowFromCenter(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__lowerCamelCase , run_time=1.5 ) ) self.play(*__lowerCamelCase ) self.play(*__lowerCamelCase ) self.wait()
698
0
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_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A : List[str] = logging.get_logger(__name__) def __a ( A__ : Dict ): if isinstance(A__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(A__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(A__ ): return [[videos]] raise ValueError(F"Could not make batched video from {videos}" ) class _SCREAMING_SNAKE_CASE ( snake_case__ ): '''simple docstring''' lowerCamelCase__ = ['''pixel_values'''] def __init__( self : List[str] , __lowerCamelCase : Optional[int] = True , __lowerCamelCase : Tuple = None , __lowerCamelCase : List[str] = PILImageResampling.BILINEAR , __lowerCamelCase : Any = True , __lowerCamelCase : List[Any] = None , __lowerCamelCase : Dict = True , __lowerCamelCase : int = 1 / 255 , __lowerCamelCase : Tuple = True , __lowerCamelCase : int = None , __lowerCamelCase : Tuple = None , **__lowerCamelCase : Optional[int] , ): super().__init__(**_A ) SCREAMING_SNAKE_CASE = size if size is not None else {'shortest_edge': 224} SCREAMING_SNAKE_CASE = get_size_dict(_A , default_to_square=_A ) SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {'height': 224, 'width': 224} SCREAMING_SNAKE_CASE = get_size_dict(_A , param_name="crop_size" ) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = do_center_crop SCREAMING_SNAKE_CASE = crop_size SCREAMING_SNAKE_CASE = resample SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD def _snake_case ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] = PILImageResampling.BILINEAR , __lowerCamelCase : int = None , **__lowerCamelCase : List[str] , ): SCREAMING_SNAKE_CASE = get_size_dict(_A , default_to_square=_A ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE = get_resize_output_image_size(_A , size["shortest_edge"] , default_to_square=_A ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE = (size['height'], size['width']) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def _snake_case ( self : Optional[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : str , __lowerCamelCase : Any = None , **__lowerCamelCase : str , ): SCREAMING_SNAKE_CASE = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(_A , size=(size["height"], size["width"]) , data_format=_A , **_A ) def _snake_case ( self : Dict , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[Any] = None , **__lowerCamelCase : Dict , ): return rescale(_A , scale=_A , data_format=_A , **_A ) def _snake_case ( self : List[str] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] = None , **__lowerCamelCase : Dict , ): return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def _snake_case ( self : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple = None , __lowerCamelCase : Optional[Any] = None , __lowerCamelCase : Tuple = None , __lowerCamelCase : Tuple = None , __lowerCamelCase : Dict = None , __lowerCamelCase : List[str] = None , __lowerCamelCase : Union[str, Any] = None , __lowerCamelCase : Tuple = None , __lowerCamelCase : Any = None , __lowerCamelCase : Optional[Any] = None , __lowerCamelCase : Tuple = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = to_numpy_array(_A ) if do_resize: SCREAMING_SNAKE_CASE = self.resize(image=_A , size=_A , resample=_A ) if do_center_crop: SCREAMING_SNAKE_CASE = self.center_crop(_A , size=_A ) if do_rescale: SCREAMING_SNAKE_CASE = self.rescale(image=_A , scale=_A ) if do_normalize: SCREAMING_SNAKE_CASE = self.normalize(image=_A , mean=_A , std=_A ) SCREAMING_SNAKE_CASE = to_channel_dimension_format(_A , _A ) return image def _snake_case ( self : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any = None , __lowerCamelCase : Union[str, Any] = None , __lowerCamelCase : Union[str, Any] = None , __lowerCamelCase : List[Any] = None , __lowerCamelCase : int = None , __lowerCamelCase : Dict = None , __lowerCamelCase : Dict = None , __lowerCamelCase : List[Any] = None , __lowerCamelCase : Union[str, Any] = None , __lowerCamelCase : Union[str, Any] = None , __lowerCamelCase : List[Any] = None , __lowerCamelCase : List[Any] = ChannelDimension.FIRST , **__lowerCamelCase : Any , ): SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(_A , default_to_square=_A ) SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE = get_size_dict(_A , param_name="crop_size" ) if not valid_images(_A ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) SCREAMING_SNAKE_CASE = make_batched(_A ) SCREAMING_SNAKE_CASE = [ [ self._preprocess_image( image=_A , do_resize=_A , size=_A , resample=_A , do_center_crop=_A , crop_size=_A , do_rescale=_A , rescale_factor=_A , do_normalize=_A , image_mean=_A , image_std=_A , data_format=_A , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE = {'pixel_values': videos} return BatchFeature(data=_A , tensor_type=_A )
711
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 import ANY if is_vision_available(): from PIL import Image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Any , **__lowerCamelCase : Any ): pass @is_pipeline_test @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @require_torch def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowerCamelCase ) , [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @require_tf def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @slow @require_torch def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , )
698
0
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any]=13 , __lowerCamelCase : int=32 , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : int=3 , __lowerCamelCase : List[str]=16 , __lowerCamelCase : str=[32, 64, 128] , __lowerCamelCase : List[Any]=[1, 2, 1] , __lowerCamelCase : Optional[int]=[2, 2, 4] , __lowerCamelCase : Any=2 , __lowerCamelCase : Any=2.0 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=0.0 , __lowerCamelCase : Dict=0.0 , __lowerCamelCase : int=0.1 , __lowerCamelCase : Union[str, Any]="gelu" , __lowerCamelCase : Dict=False , __lowerCamelCase : List[str]=True , __lowerCamelCase : Tuple=0.02 , __lowerCamelCase : str=1e-5 , __lowerCamelCase : List[str]=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=10 , __lowerCamelCase : List[str]=8 , __lowerCamelCase : List[Any]=["stage1", "stage2"] , __lowerCamelCase : Optional[int]=[1, 2] , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = use_absolute_embeddings SCREAMING_SNAKE_CASE = patch_norm SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = encoder_stride SCREAMING_SNAKE_CASE = out_features SCREAMING_SNAKE_CASE = out_indices def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : int ): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _snake_case ( self : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = FocalNetModel(config=__a ) model.to(__a ) model.eval() SCREAMING_SNAKE_CASE = model(__a ) SCREAMING_SNAKE_CASE = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _snake_case ( self : Optional[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = FocalNetBackbone(config=__a ) model.to(__a ) model.eval() SCREAMING_SNAKE_CASE = model(__a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = FocalNetBackbone(config=__a ) model.to(__a ) model.eval() SCREAMING_SNAKE_CASE = model(__a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = FocalNetForMaskedImageModeling(config=__a ) model.to(__a ) model.eval() SCREAMING_SNAKE_CASE = model(__a ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = FocalNetForMaskedImageModeling(__a ) model.to(__a ) model.eval() SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = model(__a ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _snake_case ( self : List[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = self.type_sequence_label_size SCREAMING_SNAKE_CASE = FocalNetForImageClassification(__a ) model.to(__a ) model.eval() SCREAMING_SNAKE_CASE = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = FocalNetForImageClassification(__a ) model.to(__a ) model.eval() SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) lowerCamelCase__ = ( {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = FocalNetModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__a , embed_dim=37 , has_text_modality=__a ) def _snake_case ( self : Dict ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : List[Any] ): return def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__a ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @unittest.skip(reason="FocalNet does not use inputs_embeds" ) def _snake_case ( self : Tuple ): pass @unittest.skip(reason="FocalNet does not use feedforward chunking" ) def _snake_case ( self : Optional[Any] ): pass def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE = model_class(__a ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) def _snake_case ( self : Any , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__a , __a ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__a ) , __a ) # FocalNet has a different seq_length SCREAMING_SNAKE_CASE = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) SCREAMING_SNAKE_CASE = outputs.reshaped_hidden_states self.assertEqual(len(__a ) , __a ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = reshaped_hidden_states[0].shape SCREAMING_SNAKE_CASE = ( reshaped_hidden_states[0].view(__a , __a , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(__a , __a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(__a , __a , __a , __a ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(__a , __a , __a , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(__a , __a , __a , (padded_height, padded_width) ) @slow def _snake_case ( self : List[Any] ): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = FocalNetModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = _config_zero_init(__a ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(config=__a ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @require_vision @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Optional[Any] ): return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny" ) if is_vision_available() else None @slow def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny" ).to(__a ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_processor(images=__a , return_tensors="pt" ).to(__a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__a ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) SCREAMING_SNAKE_CASE = torch.tensor([0.2_166, -0.4_368, 0.2_191] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 281 ) @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (FocalNetBackbone,) if is_torch_available() else () lowerCamelCase__ = FocalNetConfig lowerCamelCase__ = False def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = FocalNetModelTester(self )
712
__A : dict[str, float] = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.6_0217_6634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def __a ( A__ : str , A__ : str , A__ : float ): if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: SCREAMING_SNAKE_CASE = ( F"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" F"Valid values are: {', '.join(A__ )}" ) raise ValueError(A__ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
698
0
'''simple docstring''' from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict=13 , __lowerCamelCase : Union[str, Any]=30 , __lowerCamelCase : Any=2 , __lowerCamelCase : str=3 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : List[Any]=32 , __lowerCamelCase : Tuple=2 , __lowerCamelCase : Any=4 , __lowerCamelCase : Dict=37 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : Any=10 , __lowerCamelCase : str=0.02 , __lowerCamelCase : int=3 , __lowerCamelCase : Optional[int]=None , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE = num_patches + 1 def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[Any] ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase_ , initializer_range=self.initializer_range , ) def _snake_case ( self : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = TFViTModel(config=lowerCamelCase_ ) SCREAMING_SNAKE_CASE = model(lowerCamelCase_ , training=lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. SCREAMING_SNAKE_CASE = self.image_size // 2 SCREAMING_SNAKE_CASE = pixel_values[:, :, :image_size, :image_size] SCREAMING_SNAKE_CASE = model(lowerCamelCase_ , interpolate_pos_encoding=lowerCamelCase_ , training=lowerCamelCase_ ) SCREAMING_SNAKE_CASE = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.type_sequence_label_size SCREAMING_SNAKE_CASE = TFViTForImageClassification(lowerCamelCase_ ) SCREAMING_SNAKE_CASE = model(lowerCamelCase_ , labels=lowerCamelCase_ , training=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. SCREAMING_SNAKE_CASE = self.image_size // 2 SCREAMING_SNAKE_CASE = pixel_values[:, :, :image_size, :image_size] SCREAMING_SNAKE_CASE = model(lowerCamelCase_ , interpolate_pos_encoding=lowerCamelCase_ , training=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = TFViTForImageClassification(lowerCamelCase_ ) SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = model(lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () lowerCamelCase__ = ( {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification} if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = TFViTModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=lowerCamelCase_ , has_text_modality=lowerCamelCase_ , hidden_size=37 ) def _snake_case ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def _snake_case ( self : Optional[int] ): pass @unittest.skip(reason="ViT does not use inputs_embeds" ) def _snake_case ( self : int ): pass def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(lowerCamelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase_ , tf.keras.layers.Layer ) ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(lowerCamelCase_ ) SCREAMING_SNAKE_CASE = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_ ) @slow def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = TFViTModel.from_pretrained("google/vit-base-patch16-224" ) self.assertIsNotNone(lowerCamelCase_ ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Union[str, Any] ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=lowerCamelCase_ , return_tensors="tf" ) # forward pass SCREAMING_SNAKE_CASE = model(**lowerCamelCase_ ) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) SCREAMING_SNAKE_CASE = tf.constant([-0.2_744, 0.8_215, -0.0_836] ) tf.debugging.assert_near(outputs.logits[0, :3] , lowerCamelCase_ , atol=1e-4 )
713
from collections import deque from .hash_table import HashTable class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : Optional[int] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Optional[Any] ): super().__init__(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : Dict , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.values[key] def _snake_case ( self : Union[str, Any] ): return ( sum(self.charge_factor - len(__lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__lowerCamelCase ) == 0 ): return key return super()._collision_resolution(__lowerCamelCase , __lowerCamelCase )
698
0
from bisect import bisect from itertools import accumulate def __a ( A__ : Any , A__ : str , A__ : List[str] , A__ : Optional[int] ): SCREAMING_SNAKE_CASE = sorted(zip(A__ , A__ ) , key=lambda A__ : x[0] / x[1] , reverse=A__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [i[0] for i in r], [i[1] for i in r] SCREAMING_SNAKE_CASE = list(accumulate(A__ ) ) SCREAMING_SNAKE_CASE = bisect(A__ , A__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
714
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : int = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "gpt_neo" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : str , __lowerCamelCase : Dict=50257 , __lowerCamelCase : Tuple=2048 , __lowerCamelCase : Optional[Any]=2048 , __lowerCamelCase : int=24 , __lowerCamelCase : int=[[["global", "local"], 12]] , __lowerCamelCase : int=16 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]=256 , __lowerCamelCase : Tuple="gelu_new" , __lowerCamelCase : Optional[Any]=0.0 , __lowerCamelCase : str=0.0 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[Any]=1e-5 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Dict=True , __lowerCamelCase : Dict=50256 , __lowerCamelCase : Optional[int]=50256 , **__lowerCamelCase : Dict , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_layers SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = window_size SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_dropout SCREAMING_SNAKE_CASE = embed_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = classifier_dropout SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id SCREAMING_SNAKE_CASE = attention_types SCREAMING_SNAKE_CASE = self.expand_attention_types_params(__lowerCamelCase ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " f"`config.num_layers = {self.num_layers}`. " "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) @staticmethod def _snake_case ( __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __a ( A__ : str , A__ : List[Any] , A__ : List[str] , A__ : Union[str, Any] ): import torch SCREAMING_SNAKE_CASE = input.size() SCREAMING_SNAKE_CASE = len(A__ ) SCREAMING_SNAKE_CASE = shape[dimension] SCREAMING_SNAKE_CASE = torch.arange(0 , A__ , A__ ) SCREAMING_SNAKE_CASE = torch.div(sizedim - size , A__ , rounding_mode="floor" ) + 1 SCREAMING_SNAKE_CASE = torch.arange(A__ ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE = [slice(A__ )] * rank SCREAMING_SNAKE_CASE = indices SCREAMING_SNAKE_CASE = input[s] SCREAMING_SNAKE_CASE = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(A__ ) def __a ( A__ : Union[str, Any] , A__ : Optional[int] ): import torch SCREAMING_SNAKE_CASE = torch.arange(1 , A__ ) SCREAMING_SNAKE_CASE = torch.remainder(A__ , A__ ) SCREAMING_SNAKE_CASE = remainders == 0 SCREAMING_SNAKE_CASE = candidates[divisor_indices] SCREAMING_SNAKE_CASE = torch.max(A__ ) return largest_divisor, torch.div(A__ , A__ , rounding_mode="floor" ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__lowerCamelCase , direction="inputs" ) SCREAMING_SNAKE_CASE = {0: "batch", 1: "past_sequence + sequence"} else: SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return common_inputs @property def _snake_case ( self : Optional[int] ): return self._config.num_heads def _snake_case ( self : Union[str, Any] , __lowerCamelCase : PreTrainedTokenizer , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[TensorType] = None , ): SCREAMING_SNAKE_CASE = super(__lowerCamelCase , self ).generate_dummy_inputs( __lowerCamelCase , batch_size=__lowerCamelCase , seq_length=__lowerCamelCase , is_pair=__lowerCamelCase , framework=__lowerCamelCase ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = common_inputs["input_ids"].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE = seqlen + 2 SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE = [ (torch.zeros(__lowerCamelCase ), torch.zeros(__lowerCamelCase )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE = common_inputs["attention_mask"] if self.use_past: SCREAMING_SNAKE_CASE = ordered_inputs["attention_mask"].dtype SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__lowerCamelCase , __lowerCamelCase , dtype=__lowerCamelCase )] , dim=1 ) return ordered_inputs @property def _snake_case ( self : Optional[int] ): return 13
698
0
def __a ( A__ : List[Any] = 1000000 ): SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = {1: 1} for inputa in range(2 , lowerCamelCase__ ): SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: SCREAMING_SNAKE_CASE = (3 * number) + 1 counter += 1 if inputa not in counters: SCREAMING_SNAKE_CASE = counter if counter > pre_counter: SCREAMING_SNAKE_CASE = inputa SCREAMING_SNAKE_CASE = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __A : Any = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask __A : Dict = logging.getLogger(__name__) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "token-classification" def __init__( self : str , __lowerCamelCase : Any ): if type(lowercase_ ) == dict: SCREAMING_SNAKE_CASE = Namespace(**lowercase_ ) SCREAMING_SNAKE_CASE = import_module("tasks" ) try: SCREAMING_SNAKE_CASE = getattr(lowercase_ , hparams.task_type ) SCREAMING_SNAKE_CASE = token_classification_task_clazz() except AttributeError: raise ValueError( f"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) SCREAMING_SNAKE_CASE = self.token_classification_task.get_labels(hparams.labels ) SCREAMING_SNAKE_CASE = CrossEntropyLoss().ignore_index super().__init__(lowercase_ , len(self.labels ) , self.mode ) def _snake_case ( self : List[Any] , **__lowerCamelCase : Optional[int] ): return self.model(**lowercase_ ) def _snake_case ( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE = self(**lowercase_ ) SCREAMING_SNAKE_CASE = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = self.hparams for mode in ["train", "dev", "test"]: SCREAMING_SNAKE_CASE = self._feature_file(lowercase_ ) if os.path.exists(lowercase_ ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , lowercase_ ) SCREAMING_SNAKE_CASE = torch.load(lowercase_ ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) SCREAMING_SNAKE_CASE = self.token_classification_task.read_examples_from_file(args.data_dir , lowercase_ ) SCREAMING_SNAKE_CASE = self.token_classification_task.convert_examples_to_features( lowercase_ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["xlnet"] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["xlnet"] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=lowercase_ , pad_on_left=bool(self.config.model_type in ["xlnet"] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("Saving features into cached file %s" , lowercase_ ) torch.save(lowercase_ , lowercase_ ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : bool = False ): SCREAMING_SNAKE_CASE = self._feature_file(lowercase_ ) logger.info("Loading features from cached file %s" , lowercase_ ) SCREAMING_SNAKE_CASE = torch.load(lowercase_ ) SCREAMING_SNAKE_CASE = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: SCREAMING_SNAKE_CASE = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: SCREAMING_SNAKE_CASE = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) SCREAMING_SNAKE_CASE = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) , batch_size=lowercase_ ) def _snake_case ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : str ): """Compute validation""" "" SCREAMING_SNAKE_CASE = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE = self(**lowercase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = outputs[:2] SCREAMING_SNAKE_CASE = logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _snake_case ( self : Optional[Any] , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = torch.stack([x["val_loss"] for x in outputs] ).mean() SCREAMING_SNAKE_CASE = np.concatenate([x["pred"] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE = np.argmax(lowercase_ , axis=2 ) SCREAMING_SNAKE_CASE = np.concatenate([x["target"] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE = dict(enumerate(self.labels ) ) SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) SCREAMING_SNAKE_CASE = { "val_loss": val_loss_mean, "accuracy_score": accuracy_score(lowercase_ , lowercase_ ), "precision": precision_score(lowercase_ , lowercase_ ), "recall": recall_score(lowercase_ , lowercase_ ), "f1": fa_score(lowercase_ , lowercase_ ), } SCREAMING_SNAKE_CASE = dict(results.items() ) SCREAMING_SNAKE_CASE = results return ret, preds_list, out_label_list def _snake_case ( self : int , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._eval_end(lowercase_ ) SCREAMING_SNAKE_CASE = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _snake_case ( self : List[Any] , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._eval_end(lowercase_ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 SCREAMING_SNAKE_CASE = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _snake_case ( __lowerCamelCase : List[str] , __lowerCamelCase : int ): BaseTransformer.add_model_specific_args(lowercase_ , lowercase_ ) parser.add_argument( "--task_type" , default="NER" , type=lowercase_ , help="Task type to fine tune in training (e.g. NER, POS, etc)" ) parser.add_argument( "--max_seq_length" , default=128 , type=lowercase_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--labels" , default="" , type=lowercase_ , help="Path to a file containing all labels. If not specified, CoNLL-2003 labels are used." , ) parser.add_argument( "--gpus" , default=0 , type=lowercase_ , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) __A : Optional[Any] = NERTransformer.add_model_specific_args(parser, os.getcwd()) __A : List[str] = parser.parse_args() __A : str = NERTransformer(args) __A : str = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 __A : Tuple = sorted(glob.glob(os.path.join(args.output_dir, 'checkpoint-epoch=*.ckpt'), recursive=True)) __A : Optional[int] = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
716
import cmath import math def __a ( A__ : float , A__ : float , A__ : float , A__ : float ): SCREAMING_SNAKE_CASE = math.radians(A__ ) SCREAMING_SNAKE_CASE = math.radians(A__ ) # Convert voltage and current to rectangular form SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
698
0
from importlib import import_module from .logging import get_logger __A : Tuple = get_logger(__name__) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int]=None ): SCREAMING_SNAKE_CASE = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__" ): setattr(self , lowerCAmelCase_ , getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE = module._original_module if isinstance(lowerCAmelCase_ , _PatchedModuleObj ) else module class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowerCamelCase__ = [] def __init__( self : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any]=None ): SCREAMING_SNAKE_CASE = obj SCREAMING_SNAKE_CASE = target SCREAMING_SNAKE_CASE = new SCREAMING_SNAKE_CASE = target.split("." )[0] SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = attrs or [] def __enter__( self : Any ): *SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.target.split("." ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(lowerCAmelCase_ ) ): try: SCREAMING_SNAKE_CASE = import_module(".".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): SCREAMING_SNAKE_CASE = getattr(self.obj , lowerCAmelCase_ ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(lowerCAmelCase_ , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): SCREAMING_SNAKE_CASE = obj_attr # patch at top level setattr(self.obj , lowerCAmelCase_ , _PatchedModuleObj(lowerCAmelCase_ , attrs=self.attrs ) ) SCREAMING_SNAKE_CASE = getattr(self.obj , lowerCAmelCase_ ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(lowerCAmelCase_ , lowerCAmelCase_ , _PatchedModuleObj(getattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , attrs=self.attrs ) ) SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # finally set the target attribute setattr(lowerCAmelCase_ , lowerCAmelCase_ , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: SCREAMING_SNAKE_CASE = getattr(import_module(".".join(lowerCAmelCase_ ) ) , lowerCAmelCase_ ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , lowerCAmelCase_ ) is attr_value: SCREAMING_SNAKE_CASE = getattr(self.obj , lowerCAmelCase_ ) setattr(self.obj , lowerCAmelCase_ , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" SCREAMING_SNAKE_CASE = globals()["__builtins__"][target_attr] setattr(self.obj , lowerCAmelCase_ , self.new ) else: raise RuntimeError(f"Tried to patch attribute {target_attr} instead of a submodule." ) def __exit__( self : str , *__lowerCamelCase : Tuple ): for attr in list(self.original ): setattr(self.obj , lowerCAmelCase_ , self.original.pop(lowerCAmelCase_ ) ) def _snake_case ( self : List[str] ): self.__enter__() self._active_patches.append(self ) def _snake_case ( self : Any ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
717
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(A__ , A__ ) def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(A__ , A__ , bias=A__ ) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def __a ( A__ : Tuple , A__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = {} for old_key in state_dict.keys(): SCREAMING_SNAKE_CASE = old_key if "moe_layer.experts." in key: if expert_idx is not None: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts.0" , F"ffn.experts.expert_{expert_idx}" ) else: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: SCREAMING_SNAKE_CASE = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: SCREAMING_SNAKE_CASE = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("final_layer_norm" , "ff_layer_norm" ) SCREAMING_SNAKE_CASE = state_dict[old_key] return new_dict def __a ( A__ : List[str] , A__ : List[Any] , A__ : str , A__ : Union[str, Any] , A__ : str = WEIGHTS_NAME ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 os.makedirs(A__ , exist_ok=A__ ) for expert in range(A__ ): SCREAMING_SNAKE_CASE = switch_checkpoint_path + F"-rank-{expert}.pt" if os.path.isfile(A__ ): SCREAMING_SNAKE_CASE = torch.load(A__ )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = os.path.join( A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) torch.save(A__ , A__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A__ )[0]].dtype ) # Add the last block SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) SCREAMING_SNAKE_CASE = torch.load(switch_checkpoint_path + "-shared.pt" )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A__ ) == 1: SCREAMING_SNAKE_CASE = os.path.join(A__ , A__ ) torch.save(A__ , A__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A__ , A__ ) # Otherwise, let's build the index SCREAMING_SNAKE_CASE = {} for idx, shard in enumerate(A__ ): SCREAMING_SNAKE_CASE = weights_name.replace(".bin" , F"-{idx+1:05d}-of-{len(A__ ):05d}.bin" ) SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(A__ , os.path.join(A__ , A__ ) ) for key in shard: SCREAMING_SNAKE_CASE = shard_file # Add the metadata SCREAMING_SNAKE_CASE = {"total_size": total_size} SCREAMING_SNAKE_CASE = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(A__ , A__ ) , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE = json.dumps(A__ , indent=2 , sort_keys=A__ ) + "\n" f.write(A__ ) return metadata, index if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) __A : Optional[int] = parser.parse_args() __A , __A : Union[str, Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_2_8, args.dtype, ) __A : Any = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8 ) config.save_pretrained(args.pytorch_dump_folder_path) __A : Any = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
698
0
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = LongformerTokenizer lowerCamelCase__ = True lowerCamelCase__ = LongformerTokenizerFast lowerCamelCase__ = True def _snake_case ( self : str ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) SCREAMING_SNAKE_CASE = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def _snake_case ( self : Dict , **__lowerCamelCase : Optional[int] ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def _snake_case ( self : Any , **__lowerCamelCase : Tuple ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def _snake_case ( self : Any , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = '''lower newer''' SCREAMING_SNAKE_CASE = '''lower newer''' return input_text, output_text def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE = '''lower newer''' SCREAMING_SNAKE_CASE = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) # , add_prefix_space=True) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = self.get_tokenizer() self.assertListEqual(tokenizer.encode("Hello world!" , add_special_tokens=UpperCAmelCase__ ) , [0, 31414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("Hello world! cécé herlolip 418" , add_special_tokens=UpperCAmelCase__ ) , [0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2] , ) @slow def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained("allenai/longformer-base-4096" ) SCREAMING_SNAKE_CASE = tokenizer.encode("sequence builders" , add_special_tokens=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.encode("multi-sequence build" , add_special_tokens=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.encode( "sequence builders" , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.encode( "sequence builders" , "multi-sequence build" , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = '''Encode this sequence.''' SCREAMING_SNAKE_CASE = tokenizer.byte_encoder[''' '''.encode("utf-8" )[0]] # Testing encoder arguments SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) tokenizer.add_special_tokens({"bos_token": "<s>"} ) SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Testing spaces after special tokens SCREAMING_SNAKE_CASE = '''<mask>''' tokenizer.add_special_tokens( {"mask_token": AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ )} ) # mask token has a left space SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = '''Encode <mask> sequence''' SCREAMING_SNAKE_CASE = '''Encode <mask>sequence''' SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = encoded.index(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = encoded.index(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def _snake_case ( self : Optional[Any] ): pass def _snake_case ( self : Optional[Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = '''A, <mask> AllenNLP sentence.''' SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_p.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , ) SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( UpperCAmelCase__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( UpperCAmelCase__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) def _snake_case ( self : int ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) SCREAMING_SNAKE_CASE = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["add_prefix_space"] , UpperCAmelCase__ ) self.assertEqual(post_processor_state["add_prefix_space"] , UpperCAmelCase__ ) self.assertEqual(post_processor_state["trim_offsets"] , UpperCAmelCase__ ) def _snake_case ( self : Optional[int] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` SCREAMING_SNAKE_CASE = f"{text_of_1_token} {text_of_1_token}" SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ), len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ), len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE = f" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ), 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ), 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , )
718
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = BlipImageProcessor() SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" ) SCREAMING_SNAKE_CASE = BlipProcessor(__lowerCamelCase , __lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self : Dict , **__lowerCamelCase : Any ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).tokenizer def _snake_case ( self : List[Any] , **__lowerCamelCase : Optional[Any] ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).image_processor def _snake_case ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__lowerCamelCase , padding_value=1.0 ) SCREAMING_SNAKE_CASE = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCamelCase ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = image_processor(__lowerCamelCase , return_tensors="np" ) SCREAMING_SNAKE_CASE = processor(images=__lowerCamelCase , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
698
0
import glob import os import random from string import ascii_lowercase, digits import cva __A : Tuple = """""" __A : Optional[Any] = """""" __A : Optional[int] = """""" __A : int = 1 # (0 is vertical, 1 is horizontal) def __a ( ): SCREAMING_SNAKE_CASE = get_dataset(A__ , A__ ) print("Processing..." ) SCREAMING_SNAKE_CASE = update_image_and_anno(A__ , A__ , A__ ) for index, image in enumerate(A__ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE = random_chars(32 ) SCREAMING_SNAKE_CASE = paths[index].split(os.sep )[-1].rsplit("." , 1 )[0] SCREAMING_SNAKE_CASE = F"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cva.imwrite(F"/{file_root}.jpg" , A__ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"Success {index+1}/{len(A__ )} with {file_name}" ) SCREAMING_SNAKE_CASE = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE = F"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(A__ ) with open(F"/{file_root}.txt" , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def __a ( A__ : str , A__ : int ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for label_file in glob.glob(os.path.join(A__ , "*.txt" ) ): SCREAMING_SNAKE_CASE = label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(A__ ) as in_file: SCREAMING_SNAKE_CASE = in_file.readlines() SCREAMING_SNAKE_CASE = os.path.join(A__ , F"{label_name}.jpg" ) SCREAMING_SNAKE_CASE = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE = obj_list.rstrip("\n" ).split(" " ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(A__ ) labels.append(A__ ) return img_paths, labels def __a ( A__ : Any , A__ : Optional[Any] , A__ : str = 1 ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for idx in range(len(A__ ) ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = img_list[idx] path_list.append(A__ ) SCREAMING_SNAKE_CASE = anno_list[idx] SCREAMING_SNAKE_CASE = cva.imread(A__ ) if flip_type == 1: SCREAMING_SNAKE_CASE = cva.flip(A__ , A__ ) for bbox in img_annos: SCREAMING_SNAKE_CASE = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE = cva.flip(A__ , A__ ) for bbox in img_annos: SCREAMING_SNAKE_CASE = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(A__ ) new_imgs_list.append(A__ ) return new_imgs_list, new_annos_lists, path_list def __a ( A__ : Optional[int] = 32 ): assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE = ascii_lowercase + digits return "".join(random.choice(A__ ) for _ in range(A__ ) ) if __name__ == "__main__": main() print('DONE ✅')
719
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, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Union[str, Any] ): pass def __a ( A__ : str ): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A : Tuple = ( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def _snake_case ( self : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model=__lowerCamelCase , tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) SCREAMING_SNAKE_CASE = "What is the placebo?" SCREAMING_SNAKE_CASE = [ { "image": load_image(__lowerCamelCase ), "question": question, }, { "image": image, "question": question, }, { "image": image, "question": question, "word_boxes": word_boxes, }, ] return dqa_pipeline, examples def _snake_case ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = dqa_pipeline(__lowerCamelCase , top_k=2 ) self.assertEqual( __lowerCamelCase , [ [ {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = pipeline("document-question-answering" , model="hf-internal-testing/tiny-random-layoutlmv2" ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "How many cats are there?" SCREAMING_SNAKE_CASE = [ {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) # We can optionnally pass directly the words and bounding boxes SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , words=__lowerCamelCase , boxes=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) @slow @require_torch def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="naver-clova-ix/donut-base-finetuned-docvqa" , tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa" ) , feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , [{"answer": "us-001"}] ) @require_tf @unittest.skip("Document question answering not implemented in TF" ) def _snake_case ( self : List[Any] ): pass
698
0
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="session" ) def __a ( ): SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string" ) ), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"] ) ), "answers": datasets.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), "id": datasets.Value("int64" ), } ) SCREAMING_SNAKE_CASE = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(__a ) ), } , features=__a , ) return dataset @pytest.fixture(scope="session" ) def __a ( A__ : Tuple , A__ : List[str] ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "file.arrow" ) dataset.map(cache_file_name=__a ) return filename # FILE_CONTENT + files __A : str = '\\n Text data.\n Second line of data.' @pytest.fixture(scope="session" ) def __a ( A__ : List[Any] ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt" SCREAMING_SNAKE_CASE = FILE_CONTENT with open(__a , "w" ) as f: f.write(__a ) return filename @pytest.fixture(scope="session" ) def __a ( A__ : str ): import bza SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt.bz2" SCREAMING_SNAKE_CASE = bytes(__a , "utf-8" ) with bza.open(__a , "wb" ) as f: f.write(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Union[str, Any] ): import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "file.txt.gz" ) SCREAMING_SNAKE_CASE = bytes(__a , "utf-8" ) with gzip.open(__a , "wb" ) as f: f.write(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Any ): if datasets.config.LZ4_AVAILABLE: import lza.frame SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt.lz4" SCREAMING_SNAKE_CASE = bytes(__a , "utf-8" ) with lza.frame.open(__a , "wb" ) as f: f.write(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Dict , A__ : Any ): if datasets.config.PY7ZR_AVAILABLE: import pyazr SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt.7z" with pyazr.SevenZipFile(__a , "w" ) as archive: archive.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Union[str, Any] , A__ : int ): import tarfile SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt.tar" with tarfile.TarFile(__a , "w" ) as f: f.add(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Any ): import lzma SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt.xz" SCREAMING_SNAKE_CASE = bytes(__a , "utf-8" ) with lzma.open(__a , "wb" ) as f: f.write(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : List[Any] , A__ : str ): import zipfile SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Dict ): if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.txt.zst" SCREAMING_SNAKE_CASE = bytes(__a , "utf-8" ) with zstd.open(__a , "wb" ) as f: f.write(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : int ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "file.xml" SCREAMING_SNAKE_CASE = textwrap.dedent( "\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>" ) with open(__a , "w" ) as f: f.write(__a ) return filename __A : List[str] = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] __A : Optional[int] = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] __A : Optional[Any] = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } __A : Optional[Any] = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] __A : Any = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope="session" ) def __a ( ): return DATA_DICT_OF_LISTS @pytest.fixture(scope="session" ) def __a ( A__ : Optional[Any] ): SCREAMING_SNAKE_CASE = datasets.Dataset.from_dict(__a ) SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.arrow" ) dataset.map(cache_file_name=__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Union[str, Any] ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.sqlite" ) with contextlib.closing(sqlitea.connect(__a ) ) as con: SCREAMING_SNAKE_CASE = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)" ) for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="session" ) def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.csv" ) with open(__a , "w" , newline="" ) as f: SCREAMING_SNAKE_CASE = csv.DictWriter(__a , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : str ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset2.csv" ) with open(__a , "w" , newline="" ) as f: SCREAMING_SNAKE_CASE = csv.DictWriter(__a , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[int] , A__ : Union[str, Any] ): import bza SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.csv.bz2" with open(__a , "rb" ) as f: SCREAMING_SNAKE_CASE = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(__a , "wb" ) as f: f.write(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[Any] , A__ : List[str] , A__ : Dict ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[Any] , A__ : List[str] , A__ : Dict ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.basename(csv_path.replace(".csv" , ".CSV" ) ) ) f.write(__a , arcname=os.path.basename(csva_path.replace(".csv" , ".CSV" ) ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : str , A__ : Tuple , A__ : Any ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.csv.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.join("main_dir" , os.path.basename(__a ) ) ) f.write(__a , arcname=os.path.join("main_dir" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[Any] ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.parquet" ) SCREAMING_SNAKE_CASE = pa.schema( { "col_1": pa.string(), "col_2": pa.intaa(), "col_3": pa.floataa(), } ) with open(__a , "wb" ) as f: SCREAMING_SNAKE_CASE = pq.ParquetWriter(__a , schema=__a ) SCREAMING_SNAKE_CASE = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(__a ) )] for k in DATA[0]} , schema=__a ) writer.write_table(__a ) writer.close() return path @pytest.fixture(scope="session" ) def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) SCREAMING_SNAKE_CASE = {"data": DATA} with open(__a , "w" ) as f: json.dump(__a , __a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Union[str, Any] ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) SCREAMING_SNAKE_CASE = {"data": DATA_DICT_OF_LISTS} with open(__a , "w" ) as f: json.dump(__a , __a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : int ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl" ) with open(__a , "w" ) as f: for item in DATA: f.write(json.dumps(__a ) + "\n" ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Union[str, Any] ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset2.jsonl" ) with open(__a , "w" ) as f: for item in DATA: f.write(json.dumps(__a ) + "\n" ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset_312.jsonl" ) with open(__a , "w" ) as f: for item in DATA_312: f.write(json.dumps(__a ) + "\n" ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Dict ): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset-str.jsonl" ) with open(__a , "w" ) as f: for item in DATA_STR: f.write(json.dumps(__a ) + "\n" ) return path @pytest.fixture(scope="session" ) def __a ( A__ : str , A__ : Any ): import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.txt.gz" ) with open(__a , "rb" ) as orig_file: with gzip.open(__a , "wb" ) as zipped_file: zipped_file.writelines(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Union[str, Any] , A__ : int ): import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl.gz" ) with open(__a , "rb" ) as orig_file: with gzip.open(__a , "wb" ) as zipped_file: zipped_file.writelines(__a ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[int] , A__ : Any , A__ : int ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Dict , A__ : Union[str, Any] , A__ : Dict , A__ : str ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.join("nested" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[int] , A__ : Optional[int] , A__ : Union[str, Any] ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.join("main_dir" , os.path.basename(__a ) ) ) f.write(__a , arcname=os.path.join("main_dir" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[Any] , A__ : Dict , A__ : Dict ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.tar" with tarfile.TarFile(__a , "w" ) as f: f.add(__a , arcname=os.path.basename(__a ) ) f.add(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[int] , A__ : Any , A__ : Tuple , A__ : int ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.tar" with tarfile.TarFile(__a , "w" ) as f: f.add(__a , arcname=os.path.join("nested" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = ["0", "1", "2", "3"] SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset.txt" ) with open(__a , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def __a ( A__ : int ): SCREAMING_SNAKE_CASE = ["0", "1", "2", "3"] SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset2.txt" ) with open(__a , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Dict ): SCREAMING_SNAKE_CASE = ["0", "1", "2", "3"] SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.abc" with open(__a , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def __a ( A__ : List[Any] , A__ : Tuple , A__ : str ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.text.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Dict , A__ : List[str] , A__ : Tuple ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.text.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.join("main_dir" , os.path.basename(__a ) ) ) f.write(__a , arcname=os.path.join("main_dir" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : List[Any] , A__ : Tuple , A__ : List[str] ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.ext.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.basename("unsupported.ext" ) ) f.write(__a , arcname=os.path.basename("unsupported_2.ext" ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[int] ): SCREAMING_SNAKE_CASE = "\n".join(["First", "Second\u2029with Unicode new line", "Third"] ) SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("data" ) / "dataset_with_unicode_new_lines.txt" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(__a ) return path @pytest.fixture(scope="session" ) def __a ( ): return os.path.join("tests" , "features" , "data" , "test_image_rgb.jpg" ) @pytest.fixture(scope="session" ) def __a ( ): return os.path.join("tests" , "features" , "data" , "test_audio_44100.wav" ) @pytest.fixture(scope="session" ) def __a ( A__ : int , A__ : Optional[Any] ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data" ) / "dataset.img.zip" with zipfile.ZipFile(__a , "w" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ).replace(".jpg" , "2.jpg" ) ) return path @pytest.fixture(scope="session" ) def __a ( A__ : Optional[int] ): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("data_dir" ) (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / "subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden file with open(data_dir / "subdir" / ".test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / ".subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) return data_dir
720
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "facebook/bart-large-mnli" lowerCamelCase__ = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) lowerCamelCase__ = "text_classifier" lowerCamelCase__ = AutoTokenizer lowerCamelCase__ = AutoModelForSequenceClassification lowerCamelCase__ = ["text", ["text"]] lowerCamelCase__ = ["text"] def _snake_case ( self : Optional[Any] ): super().setup() SCREAMING_SNAKE_CASE = self.model.config SCREAMING_SNAKE_CASE = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): SCREAMING_SNAKE_CASE = int(__lowerCamelCase ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def _snake_case ( self : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = labels return self.pre_processor( [text] * len(__lowerCamelCase ) , [f"This example is {label}" for label in labels] , return_tensors="pt" , padding="max_length" , ) def _snake_case ( self : str , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = outputs.logits SCREAMING_SNAKE_CASE = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
698
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __A : Optional[int] = logging.get_logger(__name__) __A : List[str] = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""", } class _SCREAMING_SNAKE_CASE ( _snake_case , _snake_case ): '''simple docstring''' lowerCamelCase__ = """convnextv2""" def __init__( self : List[Any] , __lowerCamelCase : str=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Any=4 , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[Any]="gelu" , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Dict=1e-12 , __lowerCamelCase : List[str]=0.0 , __lowerCamelCase : int=224 , __lowerCamelCase : int=None , __lowerCamelCase : List[Any]=None , **__lowerCamelCase : Tuple , ): super().__init__(**snake_case_ ) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_stages SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = ["stem"] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=snake_case_ , out_indices=snake_case_ , stage_names=self.stage_names )
721
# 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 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __a ( A__ : str=None ): if subparsers is not None: SCREAMING_SNAKE_CASE = subparsers.add_parser("test" ) else: SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=A__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=A__ ) return parser def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: SCREAMING_SNAKE_CASE = script_name else: SCREAMING_SNAKE_CASE = F"--config_file={args.config_file} {script_name}" SCREAMING_SNAKE_CASE = ["accelerate-launch"] + test_args.split() SCREAMING_SNAKE_CASE = execute_subprocess_async(A__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __a ( ): SCREAMING_SNAKE_CASE = test_command_parser() SCREAMING_SNAKE_CASE = parser.parse_args() test_command(A__ ) if __name__ == "__main__": main()
698
0
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES __A : Any = logging.get_logger(__name__) __A : List[str] = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) __A : Any = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) __A : Any = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) __A : Tuple = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) __A : Optional[Any] = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) __A : Optional[Any] = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) __A : Dict = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) __A : List[Any] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) __A : Optional[Any] = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) __A : Optional[int] = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) __A : Optional[Any] = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) __A : Tuple = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) __A : List[Any] = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) __A : Tuple = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) __A : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) __A : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) __A : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) __A : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) __A : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) __A : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) __A : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) __A : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) __A : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) __A : str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) __A : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) __A : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) __A : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) __A : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_MAPPING __A : Dict = auto_class_update(FlaxAutoModel) class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_PRETRAINING_MAPPING __A : int = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING __A : Optional[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_MASKED_LM_MAPPING __A : int = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __A : Optional[Any] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __A : List[str] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING __A : Dict = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING __A : int = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING __A : List[Any] = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING __A : Dict = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING __A : str = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING __A : Dict = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING __A : Dict = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
700
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A : Optional[int] = logging.get_logger(__name__) __A : List[str] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } __A : Tuple = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } __A : Dict = {'facebook/blenderbot-3B': 1_2_8} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __a ( ): SCREAMING_SNAKE_CASE = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) SCREAMING_SNAKE_CASE = bs[:] SCREAMING_SNAKE_CASE = 0 for b in range(2**8 ): if b not in bs: bs.append(A__ ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE = [chr(A__ ) for n in cs] return dict(zip(A__ , A__ ) ) def __a ( A__ : Optional[int] ): SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE = char return pairs class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ["input_ids", "attention_mask"] def __init__( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any]="replace" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : List[Any]="</s>" , __lowerCamelCase : Dict="</s>" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : Optional[Any]="<unk>" , __lowerCamelCase : str="<pad>" , __lowerCamelCase : List[Any]="<mask>" , __lowerCamelCase : List[Any]=False , **__lowerCamelCase : Tuple , ): SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else bos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else eos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else sep_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else cls_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else unk_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token super().__init__( errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , **__lowerCamelCase , ) with open(__lowerCamelCase , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE = json.load(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE = bytes_to_unicode() SCREAMING_SNAKE_CASE = {v: k for k, v in self.byte_encoder.items()} with open(__lowerCamelCase , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _snake_case ( self : Dict ): return len(self.encoder ) def _snake_case ( self : int ): return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self : Tuple , __lowerCamelCase : List[str] ): if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE = min(__lowerCamelCase , key=lambda __lowerCamelCase : self.bpe_ranks.get(__lowerCamelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = bigram SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while i < len(__lowerCamelCase ): try: SCREAMING_SNAKE_CASE = word.index(__lowerCamelCase , __lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE = j if word[i] == first and i < len(__lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = new_word if len(__lowerCamelCase ) == 1: break else: SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = word return word def _snake_case ( self : str , __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for token in re.findall(self.pat , __lowerCamelCase ): SCREAMING_SNAKE_CASE = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCamelCase ).split(" " ) ) return bpe_tokens def _snake_case ( self : List[str] , __lowerCamelCase : str ): return self.encoder.get(__lowerCamelCase , self.encoder.get(self.unk_token ) ) def _snake_case ( self : Optional[int] , __lowerCamelCase : Tuple ): return self.decoder.get(__lowerCamelCase ) def _snake_case ( self : Tuple , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = "".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _snake_case ( self : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): if not os.path.isdir(__lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase ) + "\n" ) SCREAMING_SNAKE_CASE = 0 with open(__lowerCamelCase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE = token_index writer.write(" ".join(__lowerCamelCase ) + "\n" ) index += 1 return vocab_file, merge_file def _snake_case ( self : Tuple , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def _snake_case ( self : str , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : Any , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict=False , **__lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowerCamelCase ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE = " " + text return (text, kwargs) def _snake_case ( self : Dict , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): return token_ids_a + [self.eos_token_id] def _snake_case ( self : Tuple , __lowerCamelCase : "Conversation" ): SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(" " + text ) else: # Generated responses should contain them already. inputs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.encode(__lowerCamelCase ) if len(__lowerCamelCase ) > self.model_max_length: SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens." ) return input_ids
698
0
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' lowerCamelCase__ = "" lowerCamelCase__ = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowerCamelCase__ = None # compression type in fsspec. ex: "gzip" lowerCamelCase__ = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self : List[str] , __lowerCamelCase : str = "" , __lowerCamelCase : Optional[str] = None , __lowerCamelCase : Optional[dict] = None , **__lowerCamelCase : List[Any] ): super().__init__(self , **_lowerCamelCase ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode SCREAMING_SNAKE_CASE = fsspec.open( _lowerCamelCase , mode="rb" , protocol=_lowerCamelCase , compression=self.compression , client_kwargs={ "requote_redirect_url": False, # see https://github.com/huggingface/datasets/pull/5459 "trust_env": True, # Enable reading proxy env variables. **(target_options or {}).pop("client_kwargs" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) SCREAMING_SNAKE_CASE = os.path.basename(self.file.path.split("::" )[0] ) SCREAMING_SNAKE_CASE = ( self.compressed_name[: self.compressed_name.rindex("." )] if "." in self.compressed_name else self.compressed_name ) SCREAMING_SNAKE_CASE = None @classmethod def _snake_case ( cls : List[Any] , __lowerCamelCase : Tuple ): # compressed file paths are always relative to the archive root return super()._strip_protocol(_lowerCamelCase ).lstrip("/" ) def _snake_case ( self : Any ): if self.dir_cache is None: SCREAMING_SNAKE_CASE = {**self.file.fs.info(self.file.path ), "name": self.uncompressed_name} SCREAMING_SNAKE_CASE = {f["name"]: f} def _snake_case ( self : str , __lowerCamelCase : str ): return self.file.open().read() def _snake_case ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : str = "rb" , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Optional[Any]=None , **__lowerCamelCase : Optional[int] , ): SCREAMING_SNAKE_CASE = self._strip_protocol(_lowerCamelCase ) if mode != "rb": raise ValueError(f"Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'" ) return self.file.open() class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' lowerCamelCase__ = "bz2" lowerCamelCase__ = "bz2" lowerCamelCase__ = ".bz2" class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' lowerCamelCase__ = "gzip" lowerCamelCase__ = "gzip" lowerCamelCase__ = ".gz" class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' lowerCamelCase__ = "lz4" lowerCamelCase__ = "lz4" lowerCamelCase__ = ".lz4" class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' lowerCamelCase__ = "xz" lowerCamelCase__ = "xz" lowerCamelCase__ = ".xz" class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' lowerCamelCase__ = "zstd" lowerCamelCase__ = "zstd" lowerCamelCase__ = ".zst" def __init__( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : str = "rb" , __lowerCamelCase : Optional[str] = None , __lowerCamelCase : Optional[dict] = None , __lowerCamelCase : int = DEFAULT_BLOCK_SIZE , **__lowerCamelCase : int , ): super().__init__( fo=_lowerCamelCase , mode=_lowerCamelCase , target_protocol=_lowerCamelCase , target_options=_lowerCamelCase , block_size=_lowerCamelCase , **_lowerCamelCase , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 SCREAMING_SNAKE_CASE = self.file.__enter__ class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = file_ def __enter__( self : Tuple ): self._file.__enter__() return self def __exit__( self : int , *__lowerCamelCase : Tuple , **__lowerCamelCase : int ): self._file.__exit__(*_lowerCamelCase , **_lowerCamelCase ) def __iter__( self : Optional[int] ): return iter(self._file ) def _snake_case ( self : str ): return next(self._file ) def __getattr__( self : Union[str, Any] , __lowerCamelCase : Optional[Any] ): return getattr(self._file , _lowerCamelCase ) def fixed_enter(*__lowerCamelCase : Dict , **__lowerCamelCase : Any ): return WrappedFile(_enter(*_lowerCamelCase , **_lowerCamelCase ) ) SCREAMING_SNAKE_CASE = fixed_enter
701
from __future__ import annotations from cmath import sqrt def __a ( A__ : int , A__ : int , A__ : int ): if a == 0: raise ValueError("Coefficient 'a' must not be zero." ) SCREAMING_SNAKE_CASE = b * b - 4 * a * c SCREAMING_SNAKE_CASE = (-b + sqrt(A__ )) / (2 * a) SCREAMING_SNAKE_CASE = (-b - sqrt(A__ )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def __a ( ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = quadratic_roots(a=5 , b=6 , c=1 ) print(F"The solutions are: {solutiona} and {solutiona}" ) if __name__ == "__main__": main()
698
0
import argparse import os import torch from transformers.utils import WEIGHTS_NAME __A : int = ['small', 'medium', 'large'] __A : List[Any] = 'lm_head.decoder.weight' __A : str = 'lm_head.weight' def __a ( A__ : str , A__ : str ): SCREAMING_SNAKE_CASE = torch.load(lowerCamelCase_ ) SCREAMING_SNAKE_CASE = d.pop(lowerCamelCase_ ) os.makedirs(lowerCamelCase_ , exist_ok=lowerCamelCase_ ) torch.save(lowerCamelCase_ , os.path.join(lowerCamelCase_ , lowerCamelCase_ ) ) if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() parser.add_argument('--dialogpt_path', default='.', type=str) __A : str = parser.parse_args() for MODEL in DIALOGPT_MODELS: __A : int = os.path.join(args.dialogpt_path, f'{MODEL}_ft.pkl') __A : Optional[Any] = f'./DialoGPT-{MODEL}' convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
702
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_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = greedy_ids[:, input_ids.shape[1] :] SCREAMING_SNAKE_CASE = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_prompt=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("distilgpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = torch.ones((1, 5) , device=__lowerCamelCase ).long() * model.config.bos_token_id with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=1 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token SCREAMING_SNAKE_CASE = cs.out[:-1] # Remove the final "\n" SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase , timeout=0.001 ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text
698
0
from math import sqrt def __a ( A__ : Optional[Any] ): SCREAMING_SNAKE_CASE = 0 for i in range(1 , int(sqrt(UpperCamelCase__ ) + 1 ) ): if n % i == 0 and i != sqrt(UpperCamelCase__ ): total += i + n // i elif i == sqrt(UpperCamelCase__ ): total += i return total - n def __a ( A__ : Dict = 10000 ): SCREAMING_SNAKE_CASE = sum( i for i in range(1 , UpperCamelCase__ ) if sum_of_divisors(sum_of_divisors(UpperCamelCase__ ) ) == i and sum_of_divisors(UpperCamelCase__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
703
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Union[str, Any] = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __A : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
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 __a ( A__ : List[Any] ): return (data["data"], data["target"]) def __a ( A__ : Tuple , A__ : List[Any] , A__ : Union[str, Any] ): SCREAMING_SNAKE_CASE = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Predict target for test data SCREAMING_SNAKE_CASE = xgb.predict(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = predictions.reshape(len(__SCREAMING_SNAKE_CASE ) , 1 ) return predictions def __a ( ): SCREAMING_SNAKE_CASE = fetch_california_housing() SCREAMING_SNAKE_CASE = data_handling(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = train_test_split( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , test_size=0.2_5 , random_state=1 ) SCREAMING_SNAKE_CASE = xgboost(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Error printing print(F"Mean Absolute Error : {mean_absolute_error(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )}" ) print(F"Mean Square Error : {mean_squared_error(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )}" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
704
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __A : Optional[Any] = datasets.load_iris() __A : Optional[Any] = np.array(data['data']) __A : Optional[int] = np.array(data['target']) __A : Union[str, Any] = data['target_names'] __A , __A , __A , __A : Optional[int] = train_test_split(X, y) def __a ( A__ : Optional[int] , A__ : Dict ): return np.linalg.norm(np.array(A__ ) - np.array(A__ ) ) def __a ( A__ : Optional[Any] , A__ : int , A__ : Dict , A__ : Optional[Any] , A__ : Dict=5 ): SCREAMING_SNAKE_CASE = zip(A__ , A__ ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE = [] for data_point in data: SCREAMING_SNAKE_CASE = euclidean_distance(data_point[0] , A__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE = [i[1] for i in sorted(A__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE = Counter(A__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
698
0
def __a ( A__ : Any ): if not isinstance(A__ , A__ ) or number < 0: raise ValueError("Input must be a non-negative integer" ) SCREAMING_SNAKE_CASE = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
705
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 __A : Union[str, Any] = logging.get_logger(__name__) __A : Dict = { 'microsoft/resnet-50': 'https://huggingface.co/microsoft/resnet-50/blob/main/config.json', } class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ): '''simple docstring''' lowerCamelCase__ = "resnet" lowerCamelCase__ = ["basic", "bottleneck"] def __init__( self : Optional[Any] , __lowerCamelCase : int=3 , __lowerCamelCase : Dict=64 , __lowerCamelCase : str=[256, 512, 1024, 2048] , __lowerCamelCase : str=[3, 4, 6, 3] , __lowerCamelCase : Optional[int]="bottleneck" , __lowerCamelCase : int="relu" , __lowerCamelCase : List[str]=False , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : int=None , **__lowerCamelCase : Dict , ): super().__init__(**__lowerCamelCase ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embedding_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = downsample_in_first_stage SCREAMING_SNAKE_CASE = ["stem"] + [f"stage{idx}" for idx in range(1 , len(__lowerCamelCase ) + 1 )] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__lowerCamelCase , out_indices=__lowerCamelCase , stage_names=self.stage_names ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = version.parse("1.11" ) @property def _snake_case ( self : Optional[int] ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _snake_case ( self : Optional[int] ): return 1e-3
698
0
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __A : str = logging.get_logger(__name__) def __a ( A__ : nn.ModuleList , A__ : nn.ModuleList , A__ : List[int] ): SCREAMING_SNAKE_CASE = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ), F"{len(_lowerCamelCase )} != {len(_lowerCamelCase )}" dest_layers.load_state_dict(layers_to_copy.state_dict() ) __A : List[str] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __A : List[Any] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def __a ( A__ : Optional[int] , A__ : Any ): try: SCREAMING_SNAKE_CASE = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first" F" {n_student}" ) return list(range(_lowerCamelCase ) ) def __a ( A__ : Tuple , A__ : Optional[int] ): if n_student > n_teacher: raise ValueError(F"Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}" ) elif n_teacher == n_student: return list(range(_lowerCamelCase ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def __a ( A__ : Union[str, PreTrainedModel] , A__ : Union[str, Path] = "student" , A__ : Union[int, None] = None , A__ : Union[int, None] = None , A__ : int=False , A__ : Union[str, Any]=None , A__ : int=None , **A__ : Any , ): SCREAMING_SNAKE_CASE = "encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher." assert (e is not None) or (d is not None), _msg if isinstance(_lowerCamelCase , _lowerCamelCase ): AutoTokenizer.from_pretrained(_lowerCamelCase ).save_pretrained(_lowerCamelCase ) # purely for convenience SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase ).eval() else: assert isinstance(_lowerCamelCase , _lowerCamelCase ), F"teacher must be a model or string got type {type(_lowerCamelCase )}" SCREAMING_SNAKE_CASE = teacher.config.to_diff_dict() try: SCREAMING_SNAKE_CASE = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: SCREAMING_SNAKE_CASE = teacher_e if d is None: SCREAMING_SNAKE_CASE = teacher_d init_kwargs.update({"encoder_layers": e, "decoder_layers": d} ) except AttributeError: # T5 if hasattr(teacher.config , "num_encoder_layers" ): SCREAMING_SNAKE_CASE = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: SCREAMING_SNAKE_CASE = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: SCREAMING_SNAKE_CASE = teacher_e if d is None: SCREAMING_SNAKE_CASE = teacher_d if hasattr(teacher.config , "num_encoder_layers" ): init_kwargs.update({"num_encoder_layers": e, "num_decoder_layers": d} ) else: init_kwargs.update({"num_layers": e, "num_decoder_layers": d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(_lowerCamelCase ) # Copy weights SCREAMING_SNAKE_CASE = teacher.config_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_config(_lowerCamelCase ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. SCREAMING_SNAKE_CASE = student.load_state_dict(teacher.state_dict() , strict=_lowerCamelCase ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save SCREAMING_SNAKE_CASE = list(range(_lowerCamelCase ) ), list(range(_lowerCamelCase ) ) logger.info( F"Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to" F" {save_path}" ) student.save_pretrained(_lowerCamelCase ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: SCREAMING_SNAKE_CASE = pick_layers_to_copy(_lowerCamelCase , _lowerCamelCase ) if d_layers_to_copy is None: SCREAMING_SNAKE_CASE = pick_layers_to_copy(_lowerCamelCase , _lowerCamelCase ) try: if hasattr( _lowerCamelCase , "prophetnet" ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , _lowerCamelCase ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , _lowerCamelCase ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , _lowerCamelCase ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , _lowerCamelCase ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , _lowerCamelCase ) copy_layers(teacher.decoder.block , student.decoder.block , _lowerCamelCase ) logger.info( F"Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}" ) SCREAMING_SNAKE_CASE = { "teacher_type": teacher.config.model_type, "copied_encoder_layers": e_layers_to_copy, "copied_decoder_layers": d_layers_to_copy, } student.save_pretrained(_lowerCamelCase ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
706
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType __A : str = logging.get_logger(__name__) __A : Optional[Any] = { 'openai/imagegpt-small': '', 'openai/imagegpt-medium': '', 'openai/imagegpt-large': '', } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "imagegpt" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , __lowerCamelCase : Any=512 + 1 , __lowerCamelCase : str=32 * 32 , __lowerCamelCase : Any=512 , __lowerCamelCase : Optional[int]=24 , __lowerCamelCase : Tuple=8 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]="quick_gelu" , __lowerCamelCase : int=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=1e-5 , __lowerCamelCase : Optional[Any]=0.02 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : List[Any]=False , __lowerCamelCase : int=False , __lowerCamelCase : int=False , **__lowerCamelCase : Union[str, Any] , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_embd SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = tie_word_embeddings super().__init__(tie_word_embeddings=__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Optional[Any] ): return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ] ) def _snake_case ( self : Optional[int] , __lowerCamelCase : "FeatureExtractionMixin" , __lowerCamelCase : int = 1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 32 , __lowerCamelCase : int = 32 , ): SCREAMING_SNAKE_CASE = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dict(preprocessor(images=__lowerCamelCase , return_tensors=__lowerCamelCase ) ) return inputs
698
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[Any] = logging.get_logger(__name__) __A : Any = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json", "microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json", } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "markuplm" def __init__( self : Optional[Any] , __lowerCamelCase : List[Any]=30522 , __lowerCamelCase : Dict=768 , __lowerCamelCase : Optional[int]=12 , __lowerCamelCase : Tuple=12 , __lowerCamelCase : Tuple=3072 , __lowerCamelCase : List[str]="gelu" , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : str=512 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Dict=1e-12 , __lowerCamelCase : Union[str, Any]=0 , __lowerCamelCase : Tuple=0 , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : int=256 , __lowerCamelCase : Tuple=1024 , __lowerCamelCase : List[Any]=216 , __lowerCamelCase : str=1001 , __lowerCamelCase : str=32 , __lowerCamelCase : Union[str, Any]=50 , __lowerCamelCase : Tuple="absolute" , __lowerCamelCase : List[str]=True , __lowerCamelCase : int=None , **__lowerCamelCase : int , ): super().__init__( pad_token_id=__UpperCamelCase , bos_token_id=__UpperCamelCase , eos_token_id=__UpperCamelCase , **__UpperCamelCase , ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = classifier_dropout # additional properties SCREAMING_SNAKE_CASE = max_depth SCREAMING_SNAKE_CASE = max_xpath_tag_unit_embeddings SCREAMING_SNAKE_CASE = max_xpath_subs_unit_embeddings SCREAMING_SNAKE_CASE = tag_pad_id SCREAMING_SNAKE_CASE = subs_pad_id SCREAMING_SNAKE_CASE = xpath_unit_hidden_size
707
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @slow @require_torch def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("bert-base-uncased" ) SCREAMING_SNAKE_CASE = bertabert.config.encoder.vocab_size SCREAMING_SNAKE_CASE = tokenizer.sep_token_id SCREAMING_SNAKE_CASE = tokenizer.cls_token_id SCREAMING_SNAKE_CASE = 128 SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) SCREAMING_SNAKE_CASE = train_dataset.select(range(32 ) ) SCREAMING_SNAKE_CASE = val_dataset.select(range(16 ) ) SCREAMING_SNAKE_CASE = 4 def _map_to_encoder_decoder_inputs(__lowerCamelCase : str ): # Tokenizer will automatically set [BOS] <text> [EOS] SCREAMING_SNAKE_CASE = tokenizer(batch["article"] , padding="max_length" , truncation=__lowerCamelCase , max_length=512 ) SCREAMING_SNAKE_CASE = tokenizer(batch["highlights"] , padding="max_length" , truncation=__lowerCamelCase , max_length=128 ) SCREAMING_SNAKE_CASE = inputs.input_ids SCREAMING_SNAKE_CASE = inputs.attention_mask SCREAMING_SNAKE_CASE = outputs.input_ids SCREAMING_SNAKE_CASE = outputs.input_ids.copy() SCREAMING_SNAKE_CASE = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] SCREAMING_SNAKE_CASE = outputs.attention_mask assert all(len(__lowerCamelCase ) == 512 for x in inputs.input_ids ) assert all(len(__lowerCamelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(__lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = pred.label_ids SCREAMING_SNAKE_CASE = pred.predictions # all unnecessary tokens are removed SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = sum([int(pred_str[i] == label_str[i] ) for i in range(len(__lowerCamelCase ) )] ) / len(__lowerCamelCase ) return {"accuracy": accuracy} # map train dataset SCREAMING_SNAKE_CASE = train_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset SCREAMING_SNAKE_CASE = val_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE = SeqaSeqTrainingArguments( output_dir=__lowerCamelCase , per_device_train_batch_size=__lowerCamelCase , per_device_eval_batch_size=__lowerCamelCase , predict_with_generate=__lowerCamelCase , evaluation_strategy="steps" , do_train=__lowerCamelCase , do_eval=__lowerCamelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer SCREAMING_SNAKE_CASE = SeqaSeqTrainer( model=__lowerCamelCase , args=__lowerCamelCase , compute_metrics=_compute_metrics , train_dataset=__lowerCamelCase , eval_dataset=__lowerCamelCase , tokenizer=__lowerCamelCase , ) # start training trainer.train()
698
0
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __a ( A__ : bytes , A__ : int ): SCREAMING_SNAKE_CASE = F"{sampling_rate}" SCREAMING_SNAKE_CASE = """1""" SCREAMING_SNAKE_CASE = """f32le""" SCREAMING_SNAKE_CASE = [ """ffmpeg""", """-i""", """pipe:0""", """-ac""", ac, """-ar""", ar, """-f""", format_for_conversion, """-hide_banner""", """-loglevel""", """quiet""", """pipe:1""", ] try: with subprocess.Popen(A__ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: SCREAMING_SNAKE_CASE = ffmpeg_process.communicate(A__ ) except FileNotFoundError as error: raise ValueError("ffmpeg was not found but is required to load audio files from filename" ) from error SCREAMING_SNAKE_CASE = output_stream[0] SCREAMING_SNAKE_CASE = np.frombuffer(A__ , np.floataa ) if audio.shape[0] == 0: raise ValueError("Malformed soundfile" ) return audio def __a ( A__ : int , A__ : float , A__ : str = "f32le" , ): SCREAMING_SNAKE_CASE = F"{sampling_rate}" SCREAMING_SNAKE_CASE = """1""" if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE = 4 else: raise ValueError(F"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`" ) SCREAMING_SNAKE_CASE = platform.system() if system == "Linux": SCREAMING_SNAKE_CASE = """alsa""" SCREAMING_SNAKE_CASE = """default""" elif system == "Darwin": SCREAMING_SNAKE_CASE = """avfoundation""" SCREAMING_SNAKE_CASE = """:0""" elif system == "Windows": SCREAMING_SNAKE_CASE = """dshow""" SCREAMING_SNAKE_CASE = """default""" SCREAMING_SNAKE_CASE = [ """ffmpeg""", """-f""", format_, """-i""", input_, """-ac""", ac, """-ar""", ar, """-f""", format_for_conversion, """-fflags""", """nobuffer""", """-hide_banner""", """-loglevel""", """quiet""", """pipe:1""", ] SCREAMING_SNAKE_CASE = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample SCREAMING_SNAKE_CASE = _ffmpeg_stream(A__ , A__ ) for item in iterator: yield item def __a ( A__ : int , A__ : float , A__ : Optional[int] = None , A__ : Optional[Union[Tuple[float, float], float]] = None , A__ : str = "f32le" , ): if stream_chunk_s is not None: SCREAMING_SNAKE_CASE = stream_chunk_s else: SCREAMING_SNAKE_CASE = chunk_length_s SCREAMING_SNAKE_CASE = ffmpeg_microphone(A__ , A__ , format_for_conversion=A__ ) if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE = np.intaa SCREAMING_SNAKE_CASE = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE = np.floataa SCREAMING_SNAKE_CASE = 4 else: raise ValueError(F"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`" ) if stride_length_s is None: SCREAMING_SNAKE_CASE = chunk_length_s / 6 SCREAMING_SNAKE_CASE = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(A__ , (int, float) ): SCREAMING_SNAKE_CASE = [stride_length_s, stride_length_s] SCREAMING_SNAKE_CASE = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample SCREAMING_SNAKE_CASE = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample SCREAMING_SNAKE_CASE = datetime.datetime.now() SCREAMING_SNAKE_CASE = datetime.timedelta(seconds=A__ ) for item in chunk_bytes_iter(A__ , A__ , stride=(stride_left, stride_right) , stream=A__ ): # Put everything back in numpy scale SCREAMING_SNAKE_CASE = np.frombuffer(item["raw"] , dtype=A__ ) SCREAMING_SNAKE_CASE = ( item["""stride"""][0] // size_of_sample, item["""stride"""][1] // size_of_sample, ) SCREAMING_SNAKE_CASE = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __a ( A__ : List[str] , A__ : int , A__ : Tuple[int, int] , A__ : bool = False ): SCREAMING_SNAKE_CASE = B"""""" SCREAMING_SNAKE_CASE = stride if stride_left + stride_right >= chunk_len: raise ValueError( F"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}" ) SCREAMING_SNAKE_CASE = 0 for raw in iterator: acc += raw if stream and len(A__ ) < chunk_len: SCREAMING_SNAKE_CASE = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(A__ ) >= chunk_len: # We are flushing the accumulator SCREAMING_SNAKE_CASE = (_stride_left, stride_right) SCREAMING_SNAKE_CASE = {"""raw""": acc[:chunk_len], """stride""": stride} if stream: SCREAMING_SNAKE_CASE = False yield item SCREAMING_SNAKE_CASE = stride_left SCREAMING_SNAKE_CASE = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(A__ ) > stride_left: SCREAMING_SNAKE_CASE = {"""raw""": acc, """stride""": (_stride_left, 0)} if stream: SCREAMING_SNAKE_CASE = False yield item def __a ( A__ : Dict , A__ : int ): SCREAMING_SNAKE_CASE = 2**24 # 16Mo try: with subprocess.Popen(A__ , stdout=subprocess.PIPE , bufsize=A__ ) as ffmpeg_process: while True: SCREAMING_SNAKE_CASE = ffmpeg_process.stdout.read(A__ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError("ffmpeg was not found but is required to stream audio files from filename" ) from error
708
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, 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 ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , "num_attention_heads" ) ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : Optional[int]=64 , __lowerCamelCase : Dict=3 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : int=2 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Tuple=[128, 256, 384] , __lowerCamelCase : int=[4, 6, 8] , __lowerCamelCase : Tuple=[2, 3, 4] , __lowerCamelCase : List[str]=[16, 16, 16] , __lowerCamelCase : int=0 , __lowerCamelCase : List[Any]=[2, 2, 2] , __lowerCamelCase : List[str]=[2, 2, 2] , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=True , __lowerCamelCase : int=2 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = kernel_size SCREAMING_SNAKE_CASE = stride SCREAMING_SNAKE_CASE = padding SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = [ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[str] ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = LevitModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) SCREAMING_SNAKE_CASE = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def _snake_case ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = LevitForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) lowerCamelCase__ = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = LevitModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : Any ): return @unittest.skip(reason="Levit does not use inputs_embeds" ) def _snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason="Levit does not support input and output embeddings" ) def _snake_case ( self : Tuple ): pass @unittest.skip(reason="Levit does not output attentions" ) def _snake_case ( self : Tuple ): pass def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : List[Any] ): def check_hidden_states_output(__lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = len(self.model_tester.depths ) + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) SCREAMING_SNAKE_CASE = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : int ): pass def _snake_case ( self : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : int=False ): SCREAMING_SNAKE_CASE = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def _snake_case ( self : List[Any] ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(__lowerCamelCase ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(__lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.gradient_checkpointing_enable() model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(__lowerCamelCase ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}" ): SCREAMING_SNAKE_CASE = problem_type["title"] SCREAMING_SNAKE_CASE = problem_type["num_labels"] SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) SCREAMING_SNAKE_CASE = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=__lowerCamelCase ) as warning_list: SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def _snake_case ( self : List[Any] ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = LevitModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Dict ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([1.0_448, -0.3_745, -1.8_317] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
698
0
from __future__ import annotations import collections import pprint from pathlib import Path def __a ( A__ : str ): return "".join(sorted(lowerCAmelCase__ ) ) def __a ( A__ : str ): return word_by_signature[signature(lowerCAmelCase__ )] __A : List[Any] = Path(__file__).parent.joinpath('words.txt').read_text(encoding='utf-8') __A : int = sorted({word.strip().lower() for word in data.splitlines()}) __A : Union[str, Any] = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": __A : Any = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('anagrams.txt', 'w') as file: file.write('all_anagrams = \n ') file.write(pprint.pformat(all_anagrams))
709
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): return None class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : int ): return None class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = [ # (model_name, model_kwargs) ("bert-base-cased", {}), ("gpt2", {"use_cache": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : Optional[int] ): from transformers import BertModel SCREAMING_SNAKE_CASE = ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"] with NamedTemporaryFile(mode="w+t" ) as vocab_file: vocab_file.write("\n".join(__lowerCamelCase ) ) vocab_file.flush() SCREAMING_SNAKE_CASE = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: SCREAMING_SNAKE_CASE = BertModel(BertConfig(vocab_size=len(__lowerCamelCase ) ) ) model.save_pretrained(__lowerCamelCase ) self._test_export(__lowerCamelCase , "pt" , 12 , __lowerCamelCase ) @require_tf @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(Path(__lowerCamelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) @require_torch @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(__lowerCamelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) def _snake_case ( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Tuple=None , **__lowerCamelCase : List[str] ): try: # Compute path with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE = Path(__lowerCamelCase ).joinpath("model.onnx" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) return path except Exception as e: self.fail(__lowerCamelCase ) @require_torch @require_tokenizers @slow def _snake_case ( self : Dict ): from transformers import BertModel SCREAMING_SNAKE_CASE = BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "pt" ) @require_tf @require_tokenizers @slow def _snake_case ( self : int ): from transformers import TFBertModel SCREAMING_SNAKE_CASE = TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "tf" ) def _snake_case ( self : int , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = FeatureExtractionPipeline(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = infer_shapes(__lowerCamelCase , __lowerCamelCase ) # Assert all variables are present self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __lowerCamelCase ) self.assertSequenceEqual(variable_names[3:] , __lowerCamelCase ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: "batch", 1: "sequence"} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["output_0"] , {0: "batch", 1: "sequence"} ) self.assertDictEqual(shapes["output_1"] , {0: "batch"} ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask", "token_type_ids"] SCREAMING_SNAKE_CASE = {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__lowerCamelCase ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__lowerCamelCase ) , set(__lowerCamelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__lowerCamelCase , (tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncNonContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__lowerCamelCase ) , 1 ) self.assertEqual(len(__lowerCamelCase ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["input_ids"] ) self.assertEqual(ordered_input_names[0] , "input_ids" ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = generate_identified_filename(Path("/home/something/my_fake_model.onnx" ) , "-test" ) self.assertEqual("/home/something/my_fake_model-test.onnx" , generated.as_posix() )
698
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) SCREAMING_SNAKE_CASE = get_activation("gelu" ) self.assertTrue(torch.allclose(gelu_python(lowerCamelCase_ ) , torch_builtin(lowerCamelCase_ ) ) ) self.assertFalse(torch.allclose(gelu_python(lowerCamelCase_ ) , gelu_new(lowerCamelCase_ ) ) ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) SCREAMING_SNAKE_CASE = get_activation("gelu" ) SCREAMING_SNAKE_CASE = get_activation("gelu_10" ) SCREAMING_SNAKE_CASE = torch_builtin(lowerCamelCase_ ) SCREAMING_SNAKE_CASE = geluaa(lowerCamelCase_ ) SCREAMING_SNAKE_CASE = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(lowerCamelCase_ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self : Dict ): get_activation("gelu" ) get_activation("gelu_10" ) get_activation("gelu_fast" ) get_activation("gelu_new" ) get_activation("gelu_python" ) get_activation("gelu_pytorch_tanh" ) get_activation("linear" ) get_activation("mish" ) get_activation("quick_gelu" ) get_activation("relu" ) get_activation("sigmoid" ) get_activation("silu" ) get_activation("swish" ) get_activation("tanh" ) with self.assertRaises(lowerCamelCase_ ): get_activation("bogus" ) with self.assertRaises(lowerCamelCase_ ): get_activation(lowerCamelCase_ ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = get_activation("gelu" ) SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = get_activation("gelu" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(lowerCamelCase_ ): SCREAMING_SNAKE_CASE = acta.a
710
from manim import * class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("CPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("GPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Model" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): rect.set_stroke(__lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__lowerCamelCase , buff=0.0 ) self.add(__lowerCamelCase ) cpu_targs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Loaded Checkpoint" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , aligned_edge=__lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) SCREAMING_SNAKE_CASE = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = MarkupText( f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(__lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) SCREAMING_SNAKE_CASE = MarkupText( f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__lowerCamelCase ) , Write(__lowerCamelCase ) ) self.play(Write(__lowerCamelCase , run_time=1 ) , Create(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): SCREAMING_SNAKE_CASE = fill.copy().set_fill(__lowerCamelCase , opacity=0.7 ) target.move_to(__lowerCamelCase ) first_animations.append(GrowFromCenter(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__lowerCamelCase , run_time=1.5 ) ) self.play(*__lowerCamelCase ) self.play(*__lowerCamelCase ) self.wait()
698
0
import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) __A : int = logging.getLogger() def __a ( A__ : Path , A__ : list ): SCREAMING_SNAKE_CASE = "\n".join(A__ ) Path(A__ ).open("w" ).writelines(A__ ) __A : List[Any] = 'patrickvonplaten/t5-tiny-random' __A : Optional[Any] = 'sshleifer/bart-tiny-random' __A : Any = 'sshleifer/tiny-mbart' __A : Union[str, Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class _SCREAMING_SNAKE_CASE ( lowercase_ ): '''simple docstring''' def _snake_case ( self : List[Any] , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE = f"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(UpperCamelCase__ , "argv" , UpperCamelCase__ ): run_generate() assert Path(UpperCamelCase__ ).exists() # os.remove(Path(output_file_name)) def _snake_case ( self : Optional[Any] ): self.run_eval_tester(UpperCamelCase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def _snake_case ( self : Any , __lowerCamelCase : Tuple ): self.run_eval_tester(UpperCamelCase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def _snake_case ( self : Any , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE = str(tmp_dir / "val.target" ) _dump_articles(UpperCamelCase__ , text["en"] ) _dump_articles(UpperCamelCase__ , text["de"] ) SCREAMING_SNAKE_CASE = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE = f"\n run_eval_search.py\n {model}\n {str(UpperCamelCase__ )}\n {str(UpperCamelCase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(UpperCamelCase__ , "argv" , UpperCamelCase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(UpperCamelCase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(UpperCamelCase__ ).exists() os.remove(Path(UpperCamelCase__ ) )
711
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 import ANY if is_vision_available(): from PIL import Image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Any , **__lowerCamelCase : Any ): pass @is_pipeline_test @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @require_torch def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowerCamelCase ) , [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @require_tf def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @slow @require_torch def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , )
698
0
import torch from torch import nn class _SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str]=1 , __lowerCamelCase : int=False ): super().__init__() SCREAMING_SNAKE_CASE = n_token SCREAMING_SNAKE_CASE = d_embed SCREAMING_SNAKE_CASE = d_proj SCREAMING_SNAKE_CASE = cutoffs + [n_token] SCREAMING_SNAKE_CASE = [0] + self.cutoffs SCREAMING_SNAKE_CASE = div_val SCREAMING_SNAKE_CASE = self.cutoffs[0] SCREAMING_SNAKE_CASE = len(self.cutoffs ) - 1 SCREAMING_SNAKE_CASE = self.shortlist_size + self.n_clusters if self.n_clusters > 0: SCREAMING_SNAKE_CASE = nn.Parameter(torch.zeros(self.n_clusters , self.d_embed ) ) SCREAMING_SNAKE_CASE = nn.Parameter(torch.zeros(self.n_clusters ) ) SCREAMING_SNAKE_CASE = nn.ModuleList() SCREAMING_SNAKE_CASE = nn.ParameterList() if div_val == 1: for i in range(len(self.cutoffs ) ): if d_proj != d_embed: self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_ , lowerCAmelCase_ ) ) ) else: self.out_projs.append(lowerCAmelCase_ ) self.out_layers.append(nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: for i in range(len(self.cutoffs ) ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.cutoff_ends[i], self.cutoff_ends[i + 1] SCREAMING_SNAKE_CASE = d_embed // (div_val**i) self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_ , lowerCAmelCase_ ) ) ) self.out_layers.append(nn.Linear(lowerCAmelCase_ , r_idx - l_idx ) ) SCREAMING_SNAKE_CASE = keep_order def _snake_case ( self : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict ): if proj is None: SCREAMING_SNAKE_CASE = nn.functional.linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ ) else: # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1: SCREAMING_SNAKE_CASE = nn.functional.linear(lowerCAmelCase_ , proj.t().contiguous() ) SCREAMING_SNAKE_CASE = nn.functional.linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ ) # else: # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t())) # if bias is not None: # logit = logit + bias return logit def _snake_case ( self : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[Any]=False ): if labels is not None: # Shift so that tokens < n predict n SCREAMING_SNAKE_CASE = hidden[..., :-1, :].contiguous() SCREAMING_SNAKE_CASE = labels[..., 1:].contiguous() SCREAMING_SNAKE_CASE = hidden.view(-1 , hidden.size(-1 ) ) SCREAMING_SNAKE_CASE = labels.view(-1 ) if hidden.size(0 ) != labels.size(0 ): raise RuntimeError("Input and labels should have the same size in the batch dimension." ) else: SCREAMING_SNAKE_CASE = hidden.view(-1 , hidden.size(-1 ) ) if self.n_clusters == 0: SCREAMING_SNAKE_CASE = self._compute_logit(lowerCAmelCase_ , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) if labels is not None: SCREAMING_SNAKE_CASE = labels != -100 SCREAMING_SNAKE_CASE = torch.zeros_like(lowerCAmelCase_ , dtype=hidden.dtype , device=hidden.device ) SCREAMING_SNAKE_CASE = ( -nn.functional.log_softmax(lowerCAmelCase_ , dim=-1 )[mask].gather(1 , labels[mask].unsqueeze(1 ) ).squeeze(1 ) ) else: SCREAMING_SNAKE_CASE = nn.functional.log_softmax(lowerCAmelCase_ , dim=-1 ) else: # construct weights and biases SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.cutoff_ends[i], self.cutoff_ends[i + 1] SCREAMING_SNAKE_CASE = self.out_layers[0].weight[l_idx:r_idx] SCREAMING_SNAKE_CASE = self.out_layers[0].bias[l_idx:r_idx] else: SCREAMING_SNAKE_CASE = self.out_layers[i].weight SCREAMING_SNAKE_CASE = self.out_layers[i].bias if i == 0: SCREAMING_SNAKE_CASE = torch.cat([weight_i, self.cluster_weight] , dim=0 ) SCREAMING_SNAKE_CASE = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(lowerCAmelCase_ ) biases.append(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = weights[0], biases[0], self.out_projs[0] SCREAMING_SNAKE_CASE = self._compute_logit(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) SCREAMING_SNAKE_CASE = nn.functional.log_softmax(lowerCAmelCase_ , dim=1 ) if labels is None: SCREAMING_SNAKE_CASE = hidden.new_empty((head_logit.size(0 ), self.n_token) ) else: SCREAMING_SNAKE_CASE = torch.zeros_like(lowerCAmelCase_ , dtype=hidden.dtype , device=hidden.device ) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = [0] + self.cutoffs for i in range(len(lowerCAmelCase_ ) - 1 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cutoff_values[i], cutoff_values[i + 1] if labels is not None: SCREAMING_SNAKE_CASE = (labels >= l_idx) & (labels < r_idx) SCREAMING_SNAKE_CASE = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue SCREAMING_SNAKE_CASE = labels.index_select(0 , lowerCAmelCase_ ) - l_idx SCREAMING_SNAKE_CASE = head_logprob.index_select(0 , lowerCAmelCase_ ) SCREAMING_SNAKE_CASE = hidden.index_select(0 , lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE = hidden if i == 0: if labels is not None: SCREAMING_SNAKE_CASE = head_logprob_i.gather(1 , target_i[:, None] ).squeeze(1 ) else: SCREAMING_SNAKE_CASE = head_logprob[:, : self.cutoffs[0]] else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = weights[i], biases[i], self.out_projs[i] SCREAMING_SNAKE_CASE = self._compute_logit(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) SCREAMING_SNAKE_CASE = nn.functional.log_softmax(lowerCAmelCase_ , dim=1 ) SCREAMING_SNAKE_CASE = self.cutoffs[0] + i - 1 # No probability for the head cluster if labels is not None: SCREAMING_SNAKE_CASE = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather( 1 , target_i[:, None] ).squeeze(1 ) else: SCREAMING_SNAKE_CASE = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i SCREAMING_SNAKE_CASE = logprob_i if labels is not None: if (hasattr(self , "keep_order" ) and self.keep_order) or keep_order: out.index_copy_(0 , lowerCAmelCase_ , -logprob_i ) else: out[offset : offset + logprob_i.size(0 )].copy_(-logprob_i ) offset += logprob_i.size(0 ) return out def _snake_case ( self : List[Any] , __lowerCamelCase : str ): if self.n_clusters == 0: SCREAMING_SNAKE_CASE = self._compute_logit(lowerCAmelCase_ , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) return nn.functional.log_softmax(lowerCAmelCase_ , dim=-1 ) else: # construct weights and biases SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.cutoff_ends[i], self.cutoff_ends[i + 1] SCREAMING_SNAKE_CASE = self.out_layers[0].weight[l_idx:r_idx] SCREAMING_SNAKE_CASE = self.out_layers[0].bias[l_idx:r_idx] else: SCREAMING_SNAKE_CASE = self.out_layers[i].weight SCREAMING_SNAKE_CASE = self.out_layers[i].bias if i == 0: SCREAMING_SNAKE_CASE = torch.cat([weight_i, self.cluster_weight] , dim=0 ) SCREAMING_SNAKE_CASE = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(lowerCAmelCase_ ) biases.append(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = weights[0], biases[0], self.out_projs[0] SCREAMING_SNAKE_CASE = self._compute_logit(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) SCREAMING_SNAKE_CASE = hidden.new_empty((head_logit.size(0 ), self.n_token) ) SCREAMING_SNAKE_CASE = nn.functional.log_softmax(lowerCAmelCase_ , dim=1 ) SCREAMING_SNAKE_CASE = [0] + self.cutoffs for i in range(len(lowerCAmelCase_ ) - 1 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cutoff_values[i], cutoff_values[i + 1] if i == 0: SCREAMING_SNAKE_CASE = head_logprob[:, : self.cutoffs[0]] else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = weights[i], biases[i], self.out_projs[i] SCREAMING_SNAKE_CASE = self._compute_logit(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) SCREAMING_SNAKE_CASE = nn.functional.log_softmax(lowerCAmelCase_ , dim=1 ) SCREAMING_SNAKE_CASE = head_logprob[:, -i] + tail_logprob_i SCREAMING_SNAKE_CASE = logprob_i return out
712
__A : dict[str, float] = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.6_0217_6634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def __a ( A__ : str , A__ : str , A__ : float ): if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: SCREAMING_SNAKE_CASE = ( F"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" F"Valid values are: {', '.join(A__ )}" ) raise ValueError(A__ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
698
0
'''simple docstring''' import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : List[Any] = logging.get_logger(__name__) __A : Dict = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } __A : Any = { 'vocab_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'}, 'merges_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'}, } __A : Optional[Any] = { 'ctrl': 2_5_6, } __A : str = { 'Pregnancy': 1_6_8_6_2_9, 'Christianity': 7_6_7_5, 'Explain': 1_0_6_4_2_3, 'Fitness': 6_3_4_4_0, 'Saving': 6_3_1_6_3, 'Ask': 2_7_1_7_1, 'Ass': 9_5_9_8_5, 'Joke': 1_6_3_5_0_9, 'Questions': 4_5_6_2_2, 'Thoughts': 4_9_6_0_5, 'Retail': 5_2_3_4_2, 'Feminism': 1_6_4_3_3_8, 'Writing': 1_1_9_9_2, 'Atheism': 1_9_2_2_6_3, 'Netflix': 4_8_6_1_6, 'Computing': 3_9_6_3_9, 'Opinion': 4_3_2_1_3, 'Alone': 4_4_9_6_7, 'Funny': 5_8_9_1_7, 'Gaming': 4_0_3_5_8, 'Human': 4_0_8_8, 'India': 1_3_3_1, 'Joker': 7_7_1_3_8, 'Diet': 3_6_2_0_6, 'Legal': 1_1_8_5_9, 'Norman': 4_9_3_9, 'Tip': 7_2_6_8_9, 'Weight': 5_2_3_4_3, 'Movies': 4_6_2_7_3, 'Running': 2_3_4_2_5, 'Science': 2_0_9_0, 'Horror': 3_7_7_9_3, 'Confession': 6_0_5_7_2, 'Finance': 1_2_2_5_0, 'Politics': 1_6_3_6_0, 'Scary': 1_9_1_9_8_5, 'Support': 1_2_6_5_4, 'Technologies': 3_2_5_1_6, 'Teenage': 6_6_1_6_0, 'Event': 3_2_7_6_9, 'Learned': 6_7_4_6_0, 'Notion': 1_8_2_7_7_0, 'Wikipedia': 3_7_5_8_3, 'Books': 6_6_6_5, 'Extract': 7_6_0_5_0, 'Confessions': 1_0_2_7_0_1, 'Conspiracy': 7_5_9_3_2, 'Links': 6_3_6_7_4, 'Narcissus': 1_5_0_4_2_5, 'Relationship': 5_4_7_6_6, 'Relationships': 1_3_4_7_9_6, 'Reviews': 4_1_6_7_1, 'News': 4_2_5_6, 'Translation': 2_6_8_2_0, 'multilingual': 1_2_8_4_0_6, } def __a ( A__ : Optional[int] ): SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE = char SCREAMING_SNAKE_CASE = set(a_ ) return pairs class _SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = CONTROL_CODES def __init__( self : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Any="<unk>" , **__lowerCamelCase : Dict ): super().__init__(unk_token=_UpperCAmelCase , **_UpperCAmelCase ) with open(_UpperCAmelCase , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} with open(_UpperCAmelCase , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in merges] SCREAMING_SNAKE_CASE = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE = {} @property def _snake_case ( self : Optional[int] ): return len(self.encoder ) def _snake_case ( self : List[Any] ): return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self : List[str] , __lowerCamelCase : str ): if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE = tuple(_UpperCAmelCase ) SCREAMING_SNAKE_CASE = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) SCREAMING_SNAKE_CASE = get_pairs(_UpperCAmelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase , key=lambda __lowerCamelCase : self.bpe_ranks.get(_UpperCAmelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE = bigram SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while i < len(_UpperCAmelCase ): try: SCREAMING_SNAKE_CASE = word.index(_UpperCAmelCase , _UpperCAmelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE = j if word[i] == first and i < len(_UpperCAmelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE = tuple(_UpperCAmelCase ) SCREAMING_SNAKE_CASE = new_word if len(_UpperCAmelCase ) == 1: break else: SCREAMING_SNAKE_CASE = get_pairs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE = '''@@ '''.join(_UpperCAmelCase ) SCREAMING_SNAKE_CASE = word[:-4] SCREAMING_SNAKE_CASE = word return word def _snake_case ( self : int , __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = re.findall(r"\S+\n?" , _UpperCAmelCase ) for token in words: split_tokens.extend(list(self.bpe(_UpperCAmelCase ).split(" " ) ) ) return split_tokens def _snake_case ( self : int , __lowerCamelCase : Union[str, Any] ): return self.encoder.get(_UpperCAmelCase , self.encoder.get(self.unk_token ) ) def _snake_case ( self : Tuple , __lowerCamelCase : Tuple ): return self.decoder.get(_UpperCAmelCase , self.unk_token ) def _snake_case ( self : List[Any] , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = ''' '''.join(_UpperCAmelCase ).replace("@@ " , "" ).strip() return out_string def _snake_case ( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict = None ): if not os.path.isdir(_UpperCAmelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE = os.path.join( _UpperCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join( _UpperCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_UpperCAmelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_UpperCAmelCase , ensure_ascii=_UpperCAmelCase ) + "\n" ) SCREAMING_SNAKE_CASE = 0 with open(_UpperCAmelCase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE = token_index writer.write(" ".join(_UpperCAmelCase ) + "\n" ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
713
from collections import deque from .hash_table import HashTable class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : Optional[int] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Optional[Any] ): super().__init__(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : Dict , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.values[key] def _snake_case ( self : Union[str, Any] ): return ( sum(self.charge_factor - len(__lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__lowerCamelCase ) == 0 ): return key return super()._collision_resolution(__lowerCamelCase , __lowerCamelCase )
698
0
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : List[str]=13 , __lowerCamelCase : Tuple=7 , __lowerCamelCase : List[str]=True , __lowerCamelCase : str=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : List[Any]=99 , __lowerCamelCase : List[Any]=16 , __lowerCamelCase : Dict=36 , __lowerCamelCase : Optional[Any]=6 , __lowerCamelCase : Union[str, Any]=6 , __lowerCamelCase : List[Any]=6 , __lowerCamelCase : List[str]=37 , __lowerCamelCase : Dict="gelu" , __lowerCamelCase : Optional[Any]=0.1 , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Optional[Any]=512 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : str=0.02 , __lowerCamelCase : str=3 , __lowerCamelCase : Any=4 , __lowerCamelCase : Tuple=None , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = embedding_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_hidden_groups SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self : str ): return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def _snake_case ( self : Any , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = AlbertModel(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE = model(_A , attention_mask=_A , token_type_ids=_A ) SCREAMING_SNAKE_CASE = model(_A , token_type_ids=_A ) SCREAMING_SNAKE_CASE = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _snake_case ( self : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = AlbertForPreTraining(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , sentence_order_label=_A , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = AlbertForMaskedLM(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = AlbertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE = model( _A , attention_mask=_A , token_type_ids=_A , start_positions=_A , end_positions=_A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = AlbertForSequenceClassification(_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : int , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = AlbertForTokenClassification(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = AlbertForMultipleChoice(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase__ = ( { "feature-extraction": AlbertModel, "fill-mask": AlbertForMaskedLM, "question-answering": AlbertForQuestionAnswering, "text-classification": AlbertForSequenceClassification, "token-classification": AlbertForTokenClassification, "zero-shot": AlbertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ = True def _snake_case ( self : Optional[Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Dict=False ): SCREAMING_SNAKE_CASE = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class in get_values(_A ): SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_A ) SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) return inputs_dict def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AlbertModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=_A , hidden_size=37 ) def _snake_case ( self : List[str] ): self.config_tester.run_common_tests() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_A ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_A ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*_A ) @slow def _snake_case ( self : Union[str, Any] ): for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AlbertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AlbertModel.from_pretrained("albert-base-v2" ) SCREAMING_SNAKE_CASE = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_A , attention_mask=_A )[0] SCREAMING_SNAKE_CASE = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _A ) SCREAMING_SNAKE_CASE = torch.tensor( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) )
714
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : int = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "gpt_neo" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : str , __lowerCamelCase : Dict=50257 , __lowerCamelCase : Tuple=2048 , __lowerCamelCase : Optional[Any]=2048 , __lowerCamelCase : int=24 , __lowerCamelCase : int=[[["global", "local"], 12]] , __lowerCamelCase : int=16 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]=256 , __lowerCamelCase : Tuple="gelu_new" , __lowerCamelCase : Optional[Any]=0.0 , __lowerCamelCase : str=0.0 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[Any]=1e-5 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Dict=True , __lowerCamelCase : Dict=50256 , __lowerCamelCase : Optional[int]=50256 , **__lowerCamelCase : Dict , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_layers SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = window_size SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_dropout SCREAMING_SNAKE_CASE = embed_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = classifier_dropout SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id SCREAMING_SNAKE_CASE = attention_types SCREAMING_SNAKE_CASE = self.expand_attention_types_params(__lowerCamelCase ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " f"`config.num_layers = {self.num_layers}`. " "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) @staticmethod def _snake_case ( __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __a ( A__ : str , A__ : List[Any] , A__ : List[str] , A__ : Union[str, Any] ): import torch SCREAMING_SNAKE_CASE = input.size() SCREAMING_SNAKE_CASE = len(A__ ) SCREAMING_SNAKE_CASE = shape[dimension] SCREAMING_SNAKE_CASE = torch.arange(0 , A__ , A__ ) SCREAMING_SNAKE_CASE = torch.div(sizedim - size , A__ , rounding_mode="floor" ) + 1 SCREAMING_SNAKE_CASE = torch.arange(A__ ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE = [slice(A__ )] * rank SCREAMING_SNAKE_CASE = indices SCREAMING_SNAKE_CASE = input[s] SCREAMING_SNAKE_CASE = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(A__ ) def __a ( A__ : Union[str, Any] , A__ : Optional[int] ): import torch SCREAMING_SNAKE_CASE = torch.arange(1 , A__ ) SCREAMING_SNAKE_CASE = torch.remainder(A__ , A__ ) SCREAMING_SNAKE_CASE = remainders == 0 SCREAMING_SNAKE_CASE = candidates[divisor_indices] SCREAMING_SNAKE_CASE = torch.max(A__ ) return largest_divisor, torch.div(A__ , A__ , rounding_mode="floor" ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__lowerCamelCase , direction="inputs" ) SCREAMING_SNAKE_CASE = {0: "batch", 1: "past_sequence + sequence"} else: SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return common_inputs @property def _snake_case ( self : Optional[int] ): return self._config.num_heads def _snake_case ( self : Union[str, Any] , __lowerCamelCase : PreTrainedTokenizer , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[TensorType] = None , ): SCREAMING_SNAKE_CASE = super(__lowerCamelCase , self ).generate_dummy_inputs( __lowerCamelCase , batch_size=__lowerCamelCase , seq_length=__lowerCamelCase , is_pair=__lowerCamelCase , framework=__lowerCamelCase ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = common_inputs["input_ids"].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE = seqlen + 2 SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE = [ (torch.zeros(__lowerCamelCase ), torch.zeros(__lowerCamelCase )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE = common_inputs["attention_mask"] if self.use_past: SCREAMING_SNAKE_CASE = ordered_inputs["attention_mask"].dtype SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__lowerCamelCase , __lowerCamelCase , dtype=__lowerCamelCase )] , dim=1 ) return ordered_inputs @property def _snake_case ( self : Optional[int] ): return 13
698
0
# 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 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __a ( A__ : Optional[int]=None ): if subparsers is not None: SCREAMING_SNAKE_CASE = subparsers.add_parser("test" ) else: SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=UpperCAmelCase__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=UpperCAmelCase__ ) return parser def __a ( A__ : Dict ): SCREAMING_SNAKE_CASE = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: SCREAMING_SNAKE_CASE = script_name else: SCREAMING_SNAKE_CASE = F"--config_file={args.config_file} {script_name}" SCREAMING_SNAKE_CASE = ["accelerate-launch"] + test_args.split() SCREAMING_SNAKE_CASE = execute_subprocess_async(UpperCAmelCase__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __a ( ): SCREAMING_SNAKE_CASE = test_command_parser() SCREAMING_SNAKE_CASE = parser.parse_args() test_command(UpperCAmelCase__ ) if __name__ == "__main__": main()
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __A : Any = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : int = logging.get_logger(__name__) __A : List[str] = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = """roformer""" def __init__( self : Optional[int] , __lowerCamelCase : Union[str, Any]=50000 , __lowerCamelCase : str=None , __lowerCamelCase : Dict=768 , __lowerCamelCase : List[str]=12 , __lowerCamelCase : Any=12 , __lowerCamelCase : Optional[int]=3072 , __lowerCamelCase : List[str]="gelu" , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[str]=1536 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : Union[str, Any]=0.02 , __lowerCamelCase : List[Any]=1e-12 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : List[str]=False , __lowerCamelCase : Union[str, Any]=True , **__lowerCamelCase : Optional[int] , ): super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size if embedding_size is None else embedding_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = rotary_value SCREAMING_SNAKE_CASE = use_cache class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Union[str, Any] ): if self.task == "multiple-choice": SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
716
import cmath import math def __a ( A__ : float , A__ : float , A__ : float , A__ : float ): SCREAMING_SNAKE_CASE = math.radians(A__ ) SCREAMING_SNAKE_CASE = math.radians(A__ ) # Convert voltage and current to rectangular form SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
698
0
import math def __a ( A__ : Optional[int] , A__ : Any ): if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative" ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees" ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(A__ ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='malus_law')
717
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(A__ , A__ ) def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(A__ , A__ , bias=A__ ) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def __a ( A__ : Tuple , A__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = {} for old_key in state_dict.keys(): SCREAMING_SNAKE_CASE = old_key if "moe_layer.experts." in key: if expert_idx is not None: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts.0" , F"ffn.experts.expert_{expert_idx}" ) else: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: SCREAMING_SNAKE_CASE = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: SCREAMING_SNAKE_CASE = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("final_layer_norm" , "ff_layer_norm" ) SCREAMING_SNAKE_CASE = state_dict[old_key] return new_dict def __a ( A__ : List[str] , A__ : List[Any] , A__ : str , A__ : Union[str, Any] , A__ : str = WEIGHTS_NAME ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 os.makedirs(A__ , exist_ok=A__ ) for expert in range(A__ ): SCREAMING_SNAKE_CASE = switch_checkpoint_path + F"-rank-{expert}.pt" if os.path.isfile(A__ ): SCREAMING_SNAKE_CASE = torch.load(A__ )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = os.path.join( A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) torch.save(A__ , A__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A__ )[0]].dtype ) # Add the last block SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) SCREAMING_SNAKE_CASE = torch.load(switch_checkpoint_path + "-shared.pt" )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A__ ) == 1: SCREAMING_SNAKE_CASE = os.path.join(A__ , A__ ) torch.save(A__ , A__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A__ , A__ ) # Otherwise, let's build the index SCREAMING_SNAKE_CASE = {} for idx, shard in enumerate(A__ ): SCREAMING_SNAKE_CASE = weights_name.replace(".bin" , F"-{idx+1:05d}-of-{len(A__ ):05d}.bin" ) SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(A__ , os.path.join(A__ , A__ ) ) for key in shard: SCREAMING_SNAKE_CASE = shard_file # Add the metadata SCREAMING_SNAKE_CASE = {"total_size": total_size} SCREAMING_SNAKE_CASE = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(A__ , A__ ) , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE = json.dumps(A__ , indent=2 , sort_keys=A__ ) + "\n" f.write(A__ ) return metadata, index if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) __A : Optional[int] = parser.parse_args() __A , __A : Union[str, Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_2_8, args.dtype, ) __A : Any = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8 ) config.save_pretrained(args.pytorch_dump_folder_path) __A : Any = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
698
0
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _SCREAMING_SNAKE_CASE ( __lowerCAmelCase , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = VideoToVideoSDPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {"latents"} lowerCamelCase__ = False # No `output_type`. lowerCamelCase__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def _snake_case ( self : Union[str, Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=lowerCamelCase__ , set_alpha_to_one=lowerCamelCase__ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def _snake_case ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : str=0 ): SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) if str(lowerCamelCase__ ).startswith("mps" ): SCREAMING_SNAKE_CASE = torch.manual_seed(lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = { '''prompt''': '''A painting of a squirrel eating a burger''', '''video''': video, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = VideoToVideoSDPipeline(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = sd_pipe.to(lowerCamelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = '''np''' SCREAMING_SNAKE_CASE = sd_pipe(**lowerCamelCase__ ).frames SCREAMING_SNAKE_CASE = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) SCREAMING_SNAKE_CASE = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _snake_case ( self : Dict ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCamelCase__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _snake_case ( self : Any ): pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _snake_case ( self : Optional[Any] ): pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def _snake_case ( self : Any ): pass def _snake_case ( self : List[str] ): return super().test_progress_bar() @slow @skip_mps class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames SCREAMING_SNAKE_CASE = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = torch.randn((1, 10, 3, 1024, 576) , generator=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = video.to("cuda" ) SCREAMING_SNAKE_CASE = '''Spiderman is surfing''' SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ , video=lowerCamelCase__ , generator=lowerCamelCase__ , num_inference_steps=3 , output_type="pt" ).frames SCREAMING_SNAKE_CASE = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
718
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = BlipImageProcessor() SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" ) SCREAMING_SNAKE_CASE = BlipProcessor(__lowerCamelCase , __lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self : Dict , **__lowerCamelCase : Any ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).tokenizer def _snake_case ( self : List[Any] , **__lowerCamelCase : Optional[Any] ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).image_processor def _snake_case ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__lowerCamelCase , padding_value=1.0 ) SCREAMING_SNAKE_CASE = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCamelCase ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = image_processor(__lowerCamelCase , return_tensors="np" ) SCREAMING_SNAKE_CASE = processor(images=__lowerCamelCase , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
698
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : List[Any] = { 'configuration_chinese_clip': [ 'CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ChineseCLIPConfig', 'ChineseCLIPOnnxConfig', 'ChineseCLIPTextConfig', 'ChineseCLIPVisionConfig', ], 'processing_chinese_clip': ['ChineseCLIPProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = ['ChineseCLIPFeatureExtractor'] __A : str = ['ChineseCLIPImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'ChineseCLIPModel', 'ChineseCLIPPreTrainedModel', 'ChineseCLIPTextModel', 'ChineseCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
719
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, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Union[str, Any] ): pass def __a ( A__ : str ): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A : Tuple = ( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def _snake_case ( self : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model=__lowerCamelCase , tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) SCREAMING_SNAKE_CASE = "What is the placebo?" SCREAMING_SNAKE_CASE = [ { "image": load_image(__lowerCamelCase ), "question": question, }, { "image": image, "question": question, }, { "image": image, "question": question, "word_boxes": word_boxes, }, ] return dqa_pipeline, examples def _snake_case ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = dqa_pipeline(__lowerCamelCase , top_k=2 ) self.assertEqual( __lowerCamelCase , [ [ {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = pipeline("document-question-answering" , model="hf-internal-testing/tiny-random-layoutlmv2" ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "How many cats are there?" SCREAMING_SNAKE_CASE = [ {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) # We can optionnally pass directly the words and bounding boxes SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , words=__lowerCamelCase , boxes=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) @slow @require_torch def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="naver-clova-ix/donut-base-finetuned-docvqa" , tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa" ) , feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , [{"answer": "us-001"}] ) @require_tf @unittest.skip("Document question answering not implemented in TF" ) def _snake_case ( self : List[Any] ): pass
698
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : int = logging.get_logger(__name__) __A : int = { """facebook/data2vec-vision-base-ft""": ( """https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json""" ), } class _SCREAMING_SNAKE_CASE ( lowercase_ ): '''simple docstring''' lowerCamelCase__ = '''data2vec-vision''' def __init__( self : Optional[int] , __lowerCamelCase : List[str]=768 , __lowerCamelCase : int=12 , __lowerCamelCase : Any=12 , __lowerCamelCase : Any=3072 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : int=0.0 , __lowerCamelCase : List[str]=0.0 , __lowerCamelCase : Optional[int]=0.02 , __lowerCamelCase : Optional[Any]=1e-12 , __lowerCamelCase : str=224 , __lowerCamelCase : Any=16 , __lowerCamelCase : int=3 , __lowerCamelCase : Dict=False , __lowerCamelCase : Dict=False , __lowerCamelCase : List[str]=False , __lowerCamelCase : Tuple=False , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=[3, 5, 7, 11] , __lowerCamelCase : Optional[int]=[1, 2, 3, 6] , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Optional[int]=0.4 , __lowerCamelCase : Optional[Any]=256 , __lowerCamelCase : Optional[Any]=1 , __lowerCamelCase : Optional[Any]=False , __lowerCamelCase : Tuple=255 , **__lowerCamelCase : Optional[int] , ): super().__init__(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = use_mask_token SCREAMING_SNAKE_CASE = use_absolute_position_embeddings SCREAMING_SNAKE_CASE = use_relative_position_bias SCREAMING_SNAKE_CASE = use_shared_relative_position_bias SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = use_mean_pooling # decode head attributes (semantic segmentation) SCREAMING_SNAKE_CASE = out_indices SCREAMING_SNAKE_CASE = pool_scales # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE = use_auxiliary_head SCREAMING_SNAKE_CASE = auxiliary_loss_weight SCREAMING_SNAKE_CASE = auxiliary_channels SCREAMING_SNAKE_CASE = auxiliary_num_convs SCREAMING_SNAKE_CASE = auxiliary_concat_input SCREAMING_SNAKE_CASE = semantic_loss_ignore_index class _SCREAMING_SNAKE_CASE ( lowercase_ ): '''simple docstring''' lowerCamelCase__ = version.parse("1.11" ) @property def _snake_case ( self : str ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _snake_case ( self : List[Any] ): return 1e-4
720
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "facebook/bart-large-mnli" lowerCamelCase__ = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) lowerCamelCase__ = "text_classifier" lowerCamelCase__ = AutoTokenizer lowerCamelCase__ = AutoModelForSequenceClassification lowerCamelCase__ = ["text", ["text"]] lowerCamelCase__ = ["text"] def _snake_case ( self : Optional[Any] ): super().setup() SCREAMING_SNAKE_CASE = self.model.config SCREAMING_SNAKE_CASE = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): SCREAMING_SNAKE_CASE = int(__lowerCamelCase ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def _snake_case ( self : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = labels return self.pre_processor( [text] * len(__lowerCamelCase ) , [f"This example is {label}" for label in labels] , return_tensors="pt" , padding="max_length" , ) def _snake_case ( self : str , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = outputs.logits SCREAMING_SNAKE_CASE = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
698
0
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __A : Optional[Any] = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : Union[str, Any] , *__lowerCamelCase : List[str] , **__lowerCamelCase : List[Any] ): warnings.warn( "The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use MobileViTImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
721
# 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 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __a ( A__ : str=None ): if subparsers is not None: SCREAMING_SNAKE_CASE = subparsers.add_parser("test" ) else: SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=A__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=A__ ) return parser def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: SCREAMING_SNAKE_CASE = script_name else: SCREAMING_SNAKE_CASE = F"--config_file={args.config_file} {script_name}" SCREAMING_SNAKE_CASE = ["accelerate-launch"] + test_args.split() SCREAMING_SNAKE_CASE = execute_subprocess_async(A__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __a ( ): SCREAMING_SNAKE_CASE = test_command_parser() SCREAMING_SNAKE_CASE = parser.parse_args() test_command(A__ ) if __name__ == "__main__": main()
698
0
def __a ( A__ : list[int] , A__ : int ): SCREAMING_SNAKE_CASE = len(A__ ) SCREAMING_SNAKE_CASE = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): SCREAMING_SNAKE_CASE = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): SCREAMING_SNAKE_CASE = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: SCREAMING_SNAKE_CASE = subset[i - 1][j] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
700
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A : Optional[int] = logging.get_logger(__name__) __A : List[str] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } __A : Tuple = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } __A : Dict = {'facebook/blenderbot-3B': 1_2_8} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __a ( ): SCREAMING_SNAKE_CASE = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) SCREAMING_SNAKE_CASE = bs[:] SCREAMING_SNAKE_CASE = 0 for b in range(2**8 ): if b not in bs: bs.append(A__ ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE = [chr(A__ ) for n in cs] return dict(zip(A__ , A__ ) ) def __a ( A__ : Optional[int] ): SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE = char return pairs class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ["input_ids", "attention_mask"] def __init__( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any]="replace" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : List[Any]="</s>" , __lowerCamelCase : Dict="</s>" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : Optional[Any]="<unk>" , __lowerCamelCase : str="<pad>" , __lowerCamelCase : List[Any]="<mask>" , __lowerCamelCase : List[Any]=False , **__lowerCamelCase : Tuple , ): SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else bos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else eos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else sep_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else cls_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else unk_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token super().__init__( errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , **__lowerCamelCase , ) with open(__lowerCamelCase , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE = json.load(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE = bytes_to_unicode() SCREAMING_SNAKE_CASE = {v: k for k, v in self.byte_encoder.items()} with open(__lowerCamelCase , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _snake_case ( self : Dict ): return len(self.encoder ) def _snake_case ( self : int ): return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self : Tuple , __lowerCamelCase : List[str] ): if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE = min(__lowerCamelCase , key=lambda __lowerCamelCase : self.bpe_ranks.get(__lowerCamelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = bigram SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while i < len(__lowerCamelCase ): try: SCREAMING_SNAKE_CASE = word.index(__lowerCamelCase , __lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE = j if word[i] == first and i < len(__lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = new_word if len(__lowerCamelCase ) == 1: break else: SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = word return word def _snake_case ( self : str , __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for token in re.findall(self.pat , __lowerCamelCase ): SCREAMING_SNAKE_CASE = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCamelCase ).split(" " ) ) return bpe_tokens def _snake_case ( self : List[str] , __lowerCamelCase : str ): return self.encoder.get(__lowerCamelCase , self.encoder.get(self.unk_token ) ) def _snake_case ( self : Optional[int] , __lowerCamelCase : Tuple ): return self.decoder.get(__lowerCamelCase ) def _snake_case ( self : Tuple , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = "".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _snake_case ( self : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): if not os.path.isdir(__lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase ) + "\n" ) SCREAMING_SNAKE_CASE = 0 with open(__lowerCamelCase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE = token_index writer.write(" ".join(__lowerCamelCase ) + "\n" ) index += 1 return vocab_file, merge_file def _snake_case ( self : Tuple , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def _snake_case ( self : str , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : Any , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict=False , **__lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowerCamelCase ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE = " " + text return (text, kwargs) def _snake_case ( self : Dict , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): return token_ids_a + [self.eos_token_id] def _snake_case ( self : Tuple , __lowerCamelCase : "Conversation" ): SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(" " + text ) else: # Generated responses should contain them already. inputs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.encode(__lowerCamelCase ) if len(__lowerCamelCase ) > self.model_max_length: SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens." ) return input_ids
698
0
from math import isqrt, loga def __a ( A__ : int ): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , A__ , A__ ): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , A__ ) if is_prime[i]] def __a ( A__ : int = 800800 , A__ : int = 800800 ): SCREAMING_SNAKE_CASE = degree * loga(A__ ) SCREAMING_SNAKE_CASE = int(A__ ) SCREAMING_SNAKE_CASE = calculate_prime_numbers(A__ ) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(A__ ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'{solution() = }')
701
from __future__ import annotations from cmath import sqrt def __a ( A__ : int , A__ : int , A__ : int ): if a == 0: raise ValueError("Coefficient 'a' must not be zero." ) SCREAMING_SNAKE_CASE = b * b - 4 * a * c SCREAMING_SNAKE_CASE = (-b + sqrt(A__ )) / (2 * a) SCREAMING_SNAKE_CASE = (-b - sqrt(A__ )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def __a ( ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = quadratic_roots(a=5 , b=6 , c=1 ) print(F"The solutions are: {solutiona} and {solutiona}" ) if __name__ == "__main__": main()
698
0
import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : List[Any] , *__lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Optional[Any]=None , **__lowerCamelCase : Optional[Any] ): super().__init__(*__lowerCamelCase , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function def _snake_case ( self : Optional[int] , __lowerCamelCase : str=None , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : str = "eval" ): SCREAMING_SNAKE_CASE = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop SCREAMING_SNAKE_CASE = time.time() try: SCREAMING_SNAKE_CASE = eval_loop( __lowerCamelCase , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCamelCase , metric_key_prefix=__lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE = compute_metrics SCREAMING_SNAKE_CASE = self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( __lowerCamelCase , __lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE = self.post_process_function(__lowerCamelCase , __lowerCamelCase , output.predictions ) SCREAMING_SNAKE_CASE = self.compute_metrics(__lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): SCREAMING_SNAKE_CASE = metrics.pop(__lowerCamelCase ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE = self.callback_handler.on_evaluate(self.args , self.state , self.control , __lowerCamelCase ) return metrics def _snake_case ( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : str = "test" ): SCREAMING_SNAKE_CASE = self.get_test_dataloader(__lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop SCREAMING_SNAKE_CASE = time.time() try: SCREAMING_SNAKE_CASE = eval_loop( __lowerCamelCase , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCamelCase , metric_key_prefix=__lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE = compute_metrics SCREAMING_SNAKE_CASE = self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( __lowerCamelCase , __lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(__lowerCamelCase , __lowerCamelCase , output.predictions , "predict" ) SCREAMING_SNAKE_CASE = self.compute_metrics(__lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): SCREAMING_SNAKE_CASE = metrics.pop(__lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__lowerCamelCase )
702
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_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = greedy_ids[:, input_ids.shape[1] :] SCREAMING_SNAKE_CASE = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_prompt=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("distilgpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = torch.ones((1, 5) , device=__lowerCamelCase ).long() * model.config.bos_token_id with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=1 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token SCREAMING_SNAKE_CASE = cs.out[:-1] # Remove the final "\n" SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase , timeout=0.001 ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text
698
0
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["scripts", "external_deps", "test_metrics.py"] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 SCREAMING_SNAKE_CASE = test_metrics @require_cpu def _snake_case ( self : int ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _snake_case ( self : Tuple ): debug_launcher(self.test_metrics.main ) @require_single_gpu def _snake_case ( self : str ): self.test_metrics.main() @require_multi_gpu def _snake_case ( self : int ): print(f"Found {torch.cuda.device_count()} devices." ) SCREAMING_SNAKE_CASE = ["torchrun", f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() )
703
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Union[str, Any] = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __A : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
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 @require_tf @require_sentencepiece @require_tokenizers class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE = tokenizer("Hello there" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE = tokenizer("Hi I am" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ).loss SCREAMING_SNAKE_CASE = -tf.math.reduce_mean(__lowerCamelCase ).numpy() SCREAMING_SNAKE_CASE = -21.228_168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
704
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __A : Optional[Any] = datasets.load_iris() __A : Optional[Any] = np.array(data['data']) __A : Optional[int] = np.array(data['target']) __A : Union[str, Any] = data['target_names'] __A , __A , __A , __A : Optional[int] = train_test_split(X, y) def __a ( A__ : Optional[int] , A__ : Dict ): return np.linalg.norm(np.array(A__ ) - np.array(A__ ) ) def __a ( A__ : Optional[Any] , A__ : int , A__ : Dict , A__ : Optional[Any] , A__ : Dict=5 ): SCREAMING_SNAKE_CASE = zip(A__ , A__ ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE = [] for data_point in data: SCREAMING_SNAKE_CASE = euclidean_distance(data_point[0] , A__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE = [i[1] for i in sorted(A__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE = Counter(A__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
698
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A : Union[str, Any] = { 'configuration_m2m_100': ['M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP', 'M2M100Config', 'M2M100OnnxConfig'], 'tokenization_m2m_100': ['M2M100Tokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : str = [ 'M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST', 'M2M100ForConditionalGeneration', 'M2M100Model', 'M2M100PreTrainedModel', ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys __A : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
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 __A : Union[str, Any] = logging.get_logger(__name__) __A : Dict = { 'microsoft/resnet-50': 'https://huggingface.co/microsoft/resnet-50/blob/main/config.json', } class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ): '''simple docstring''' lowerCamelCase__ = "resnet" lowerCamelCase__ = ["basic", "bottleneck"] def __init__( self : Optional[Any] , __lowerCamelCase : int=3 , __lowerCamelCase : Dict=64 , __lowerCamelCase : str=[256, 512, 1024, 2048] , __lowerCamelCase : str=[3, 4, 6, 3] , __lowerCamelCase : Optional[int]="bottleneck" , __lowerCamelCase : int="relu" , __lowerCamelCase : List[str]=False , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : int=None , **__lowerCamelCase : Dict , ): super().__init__(**__lowerCamelCase ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embedding_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = downsample_in_first_stage SCREAMING_SNAKE_CASE = ["stem"] + [f"stage{idx}" for idx in range(1 , len(__lowerCamelCase ) + 1 )] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__lowerCamelCase , out_indices=__lowerCamelCase , stage_names=self.stage_names ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = version.parse("1.11" ) @property def _snake_case ( self : Optional[int] ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _snake_case ( self : Optional[int] ): return 1e-3
698
0
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 _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = XLMTokenizer lowerCamelCase__ = False def _snake_case ( self : Union[str, Any] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w</w>", "r</w>", "t</w>", "lo", "low", "er</w>", "low</w>", "lowest</w>", "newer</w>", "wider</w>", "<unk>", ] SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE = ["l o 123", "lo w 1456", "e r</w> 1789", ""] SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" ) as fp: fp.write(json.dumps(__lowerCamelCase ) ) with open(self.merges_file , "w" ) as fp: fp.write("\n".join(__lowerCamelCase ) ) def _snake_case ( self : Tuple , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = XLMTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE = "lower" SCREAMING_SNAKE_CASE = ["low", "er</w>"] SCREAMING_SNAKE_CASE = tokenizer.tokenize(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = tokens + ["<unk>"] SCREAMING_SNAKE_CASE = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) @slow def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = XLMTokenizer.from_pretrained("xlm-mlm-en-2048" ) SCREAMING_SNAKE_CASE = tokenizer.encode("sequence builders" , add_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.encode("multi-sequence build" , add_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase , __lowerCamelCase ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
706
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType __A : str = logging.get_logger(__name__) __A : Optional[Any] = { 'openai/imagegpt-small': '', 'openai/imagegpt-medium': '', 'openai/imagegpt-large': '', } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "imagegpt" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , __lowerCamelCase : Any=512 + 1 , __lowerCamelCase : str=32 * 32 , __lowerCamelCase : Any=512 , __lowerCamelCase : Optional[int]=24 , __lowerCamelCase : Tuple=8 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]="quick_gelu" , __lowerCamelCase : int=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=1e-5 , __lowerCamelCase : Optional[Any]=0.02 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : List[Any]=False , __lowerCamelCase : int=False , __lowerCamelCase : int=False , **__lowerCamelCase : Union[str, Any] , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_embd SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = tie_word_embeddings super().__init__(tie_word_embeddings=__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Optional[Any] ): return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ] ) def _snake_case ( self : Optional[int] , __lowerCamelCase : "FeatureExtractionMixin" , __lowerCamelCase : int = 1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 32 , __lowerCamelCase : int = 32 , ): SCREAMING_SNAKE_CASE = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dict(preprocessor(images=__lowerCamelCase , return_tensors=__lowerCamelCase ) ) return inputs
698
0
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeling_tf_common import floats_tensor from .test_framework_agnostic import GenerationIntegrationTestsMixin if is_tf_available(): import tensorflow as tf from transformers import ( AutoTokenizer, TFAutoModelForCausalLM, TFAutoModelForSeqaSeqLM, TFAutoModelForSpeechSeqaSeq, TFAutoModelForVisionaSeq, TFBartForConditionalGeneration, TFLogitsProcessorList, TFMinLengthLogitsProcessor, tf_top_k_top_p_filtering, ) if is_tensorflow_text_available(): import tensorflow_text as text @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [ [ 8.2_220_991, # 3rd highest value; idx. 0 -0.5_620_044, 5.23_229_752, 4.0_386_393, -6.8_798_378, -0.54_785_802, -3.2_012_153, 2.92_777_176, 1.88_171_953, 7.35_341_276, # 5th highest value; idx. 9 8.43_207_833, # 2nd highest value; idx. 10 -9.85_711_836, -5.96_209_236, -1.13_039_161, -7.1_115_294, -0.8_369_633, -5.3_186_408, 7.06_427_407, 0.81_369_344, -0.82_023_817, -5.9_179_796, 0.58_813_443, -6.99_778_438, 4.71_551_189, -0.18_771_637, 7.44_020_759, # 4th highest value; idx. 25 9.38_450_987, # 1st highest value; idx. 26 2.12_662_941, -9.32_562_038, 2.35_652_522, ], # cummulative prob of 5 highest values <= 0.6 [ 0.58_425_518, 4.53_139_238, -5.57_510_464, -6.28_030_699, -7.19_529_503, -4.02_122_551, 1.39_337_037, -6.06_707_057, 1.59_480_517, -9.643_119, 0.03_907_799, 0.67_231_762, -8.88_206_726, 6.27_115_922, # 4th highest value; idx. 13 2.28_520_723, 4.82_767_506, 4.30_421_368, 8.8_275_313, # 2nd highest value; idx. 17 5.44_029_958, # 5th highest value; idx. 18 -4.4_735_794, 7.38_579_536, # 3rd highest value; idx. 20 -2.91_051_663, 2.61_946_077, -2.5_674_762, -9.48_959_302, -4.02_922_645, -1.35_416_918, 9.67_702_323, # 1st highest value; idx. 27 -5.89_478_553, 1.85_370_467, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [8.222_099, 7.3_534_126, 8.432_078, 7.4_402_075, 9.38_451, 6.271_159, 8.827_531, 5.4_402_995, 7.3_857_956, 9.677_023] , dtype=tf.floataa , ) # expected non filtered values as noted above SCREAMING_SNAKE_CASE = tf_top_k_top_p_filtering(__lowerCamelCase , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 ) SCREAMING_SNAKE_CASE = output[output != -float("inf" )] SCREAMING_SNAKE_CASE = tf.cast( tf.where(tf.not_equal(__lowerCamelCase , tf.constant(-float("inf" ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1e-12 ) tf.debugging.assert_equal(__lowerCamelCase , __lowerCamelCase ) @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase , __snake_case ): '''simple docstring''' if is_tf_available(): lowerCamelCase__ = { "AutoModelForCausalLM": TFAutoModelForCausalLM, "AutoModelForSpeechSeq2Seq": TFAutoModelForSpeechSeqaSeq, "AutoModelForSeq2SeqLM": TFAutoModelForSeqaSeqLM, "AutoModelForVision2Seq": TFAutoModelForVisionaSeq, "LogitsProcessorList": TFLogitsProcessorList, "MinLengthLogitsProcessor": TFMinLengthLogitsProcessor, "create_tensor_fn": tf.convert_to_tensor, "floats_tensor": floats_tensor, "return_tensors": "tf", } @slow def _snake_case ( self : Any ): # TF-only test: tf.saved_model export SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 2 class _SCREAMING_SNAKE_CASE ( tf.Module ): '''simple docstring''' def __init__( self : Any , __lowerCamelCase : List[str] ): super(__lowerCamelCase , self ).__init__() SCREAMING_SNAKE_CASE = model @tf.function( input_signature=( tf.TensorSpec((None, input_length) , tf.intaa , name="input_ids" ), tf.TensorSpec((None, input_length) , tf.intaa , name="attention_mask" ), ) , jit_compile=__lowerCamelCase , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model.generate( input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase , max_new_tokens=__lowerCamelCase , return_dict_in_generate=__lowerCamelCase , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE = [[2, 0], [102, 103]] SCREAMING_SNAKE_CASE = [[1, 0], [1, 1]] SCREAMING_SNAKE_CASE = DummyModel(model=__lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(__lowerCamelCase , __lowerCamelCase , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE = tf.saved_model.load(__lowerCamelCase ).signatures["serving_default"] for batch_size in range(1 , len(__lowerCamelCase ) + 1 ): SCREAMING_SNAKE_CASE = { "input_ids": tf.constant(dummy_input_ids[:batch_size] ), "attention_mask": tf.constant(dummy_attention_masks[:batch_size] ), } SCREAMING_SNAKE_CASE = serving_func(**__lowerCamelCase )["sequences"] SCREAMING_SNAKE_CASE = test_model.generate(**__lowerCamelCase , max_new_tokens=__lowerCamelCase ) tf.debugging.assert_equal(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : List[str] ): # TF-only test: tf.saved_model export SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 2 class _SCREAMING_SNAKE_CASE ( tf.Module ): '''simple docstring''' def __init__( self : Tuple , __lowerCamelCase : Tuple ): super(__lowerCamelCase , self ).__init__() SCREAMING_SNAKE_CASE = model @tf.function( input_signature=( tf.TensorSpec((batch_size, None) , tf.intaa , name="input_ids" ), tf.TensorSpec((batch_size, None) , tf.intaa , name="attention_mask" ), ) , jit_compile=__lowerCamelCase , ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = self.model.generate( input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase , max_new_tokens=__lowerCamelCase , return_dict_in_generate=__lowerCamelCase , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE = [[2], [102, 103]] SCREAMING_SNAKE_CASE = [[1], [1, 1]] SCREAMING_SNAKE_CASE = DummyModel(model=__lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(__lowerCamelCase , __lowerCamelCase , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE = tf.saved_model.load(__lowerCamelCase ).signatures["serving_default"] for input_row in range(len(__lowerCamelCase ) ): SCREAMING_SNAKE_CASE = { "input_ids": tf.constant([dummy_input_ids[input_row]] ), "attention_mask": tf.constant([dummy_attention_masks[input_row]] ), } SCREAMING_SNAKE_CASE = serving_func(**__lowerCamelCase )["sequences"] SCREAMING_SNAKE_CASE = test_model.generate(**__lowerCamelCase , max_new_tokens=__lowerCamelCase ) tf.debugging.assert_equal(__lowerCamelCase , __lowerCamelCase ) @slow @require_tensorflow_text def _snake_case ( self : int ): # TF-only test: tf.saved_model export with tempfile.TemporaryDirectory() as tmp_dir: # file needed to load the TF tokenizer hf_hub_download(repo_id="google/flan-t5-small" , filename="spiece.model" , local_dir=__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : int ): super().__init__() SCREAMING_SNAKE_CASE = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(__lowerCamelCase , "spiece.model" ) , "rb" ).read() ) SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained("hf-internal-testing/tiny-random-t5" ) def _snake_case ( self : int , __lowerCamelCase : Tuple , *__lowerCamelCase : int , **__lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = self.tokenizer.tokenize(__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = text.pad_model_inputs( __lowerCamelCase , max_seq_length=64 , pad_value=self.model.config.pad_token_id ) SCREAMING_SNAKE_CASE = self.model.generate(input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase ) return self.tokenizer.detokenize(__lowerCamelCase ) SCREAMING_SNAKE_CASE = CompleteSentenceTransformer() SCREAMING_SNAKE_CASE = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name="inputs" ) SCREAMING_SNAKE_CASE = complete_model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tf.keras.Model(__lowerCamelCase , __lowerCamelCase ) keras_model.save(__lowerCamelCase ) def _snake_case ( self : Optional[Any] ): # Has PT equivalent: this test relies on random sampling SCREAMING_SNAKE_CASE = { "do_sample": True, "num_beams": 1, "top_p": 0.7, "top_k": 10, "temperature": 0.7, } SCREAMING_SNAKE_CASE = 14 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = "Hello, my dog is cute and" SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_tensors="tf" ) SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = 638 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE = model.generate(**__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) self.assertTrue(expectation == len(generated_tokens[0] ) ) SCREAMING_SNAKE_CASE = [638, 198] with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE = model.generate(**__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def _snake_case ( self : int ): # Has PT equivalent: ample use of framework-specific code SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE = "Hugging Face is a technology company based in New York and Paris." SCREAMING_SNAKE_CASE = bart_tokenizer(__lowerCamelCase , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE = TFBartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE = bart_model.generate(__lowerCamelCase ).numpy() class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : int ): return super().call(__lowerCamelCase , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = FakeBart.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE = bart_model.generate(__lowerCamelCase , foo="bar" ).numpy() self.assertTrue(np.array_equal(__lowerCamelCase , __lowerCamelCase ) ) class _SCREAMING_SNAKE_CASE ( bart_model.model.encoder.__class__ ): '''simple docstring''' def _snake_case ( self : List[str] , __lowerCamelCase : Tuple , **__lowerCamelCase : Union[str, Any] ): return super().call(__lowerCamelCase , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = FakeEncoder(bart_model.config , bart_model.model.shared ) SCREAMING_SNAKE_CASE = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) SCREAMING_SNAKE_CASE = bart_model.generate(__lowerCamelCase ).numpy() with self.assertRaises(__lowerCamelCase ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(__lowerCamelCase , foo="bar" )
707
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @slow @require_torch def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("bert-base-uncased" ) SCREAMING_SNAKE_CASE = bertabert.config.encoder.vocab_size SCREAMING_SNAKE_CASE = tokenizer.sep_token_id SCREAMING_SNAKE_CASE = tokenizer.cls_token_id SCREAMING_SNAKE_CASE = 128 SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) SCREAMING_SNAKE_CASE = train_dataset.select(range(32 ) ) SCREAMING_SNAKE_CASE = val_dataset.select(range(16 ) ) SCREAMING_SNAKE_CASE = 4 def _map_to_encoder_decoder_inputs(__lowerCamelCase : str ): # Tokenizer will automatically set [BOS] <text> [EOS] SCREAMING_SNAKE_CASE = tokenizer(batch["article"] , padding="max_length" , truncation=__lowerCamelCase , max_length=512 ) SCREAMING_SNAKE_CASE = tokenizer(batch["highlights"] , padding="max_length" , truncation=__lowerCamelCase , max_length=128 ) SCREAMING_SNAKE_CASE = inputs.input_ids SCREAMING_SNAKE_CASE = inputs.attention_mask SCREAMING_SNAKE_CASE = outputs.input_ids SCREAMING_SNAKE_CASE = outputs.input_ids.copy() SCREAMING_SNAKE_CASE = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] SCREAMING_SNAKE_CASE = outputs.attention_mask assert all(len(__lowerCamelCase ) == 512 for x in inputs.input_ids ) assert all(len(__lowerCamelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(__lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = pred.label_ids SCREAMING_SNAKE_CASE = pred.predictions # all unnecessary tokens are removed SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = sum([int(pred_str[i] == label_str[i] ) for i in range(len(__lowerCamelCase ) )] ) / len(__lowerCamelCase ) return {"accuracy": accuracy} # map train dataset SCREAMING_SNAKE_CASE = train_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset SCREAMING_SNAKE_CASE = val_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE = SeqaSeqTrainingArguments( output_dir=__lowerCamelCase , per_device_train_batch_size=__lowerCamelCase , per_device_eval_batch_size=__lowerCamelCase , predict_with_generate=__lowerCamelCase , evaluation_strategy="steps" , do_train=__lowerCamelCase , do_eval=__lowerCamelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer SCREAMING_SNAKE_CASE = SeqaSeqTrainer( model=__lowerCamelCase , args=__lowerCamelCase , compute_metrics=_compute_metrics , train_dataset=__lowerCamelCase , eval_dataset=__lowerCamelCase , tokenizer=__lowerCamelCase , ) # start training trainer.train()
698
0
import re from filelock import FileLock try: import nltk __A : List[str] = True except (ImportError, ModuleNotFoundError): __A : List[str] = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __a ( A__ : str ): re.sub("<n>" , "" , A__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(A__ ) )
708
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, 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 ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , "num_attention_heads" ) ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : Optional[int]=64 , __lowerCamelCase : Dict=3 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : int=2 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Tuple=[128, 256, 384] , __lowerCamelCase : int=[4, 6, 8] , __lowerCamelCase : Tuple=[2, 3, 4] , __lowerCamelCase : List[str]=[16, 16, 16] , __lowerCamelCase : int=0 , __lowerCamelCase : List[Any]=[2, 2, 2] , __lowerCamelCase : List[str]=[2, 2, 2] , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=True , __lowerCamelCase : int=2 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = kernel_size SCREAMING_SNAKE_CASE = stride SCREAMING_SNAKE_CASE = padding SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = [ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[str] ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = LevitModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) SCREAMING_SNAKE_CASE = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def _snake_case ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = LevitForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) lowerCamelCase__ = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = LevitModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : Any ): return @unittest.skip(reason="Levit does not use inputs_embeds" ) def _snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason="Levit does not support input and output embeddings" ) def _snake_case ( self : Tuple ): pass @unittest.skip(reason="Levit does not output attentions" ) def _snake_case ( self : Tuple ): pass def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : List[Any] ): def check_hidden_states_output(__lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = len(self.model_tester.depths ) + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) SCREAMING_SNAKE_CASE = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : int ): pass def _snake_case ( self : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : int=False ): SCREAMING_SNAKE_CASE = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def _snake_case ( self : List[Any] ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(__lowerCamelCase ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(__lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.gradient_checkpointing_enable() model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(__lowerCamelCase ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}" ): SCREAMING_SNAKE_CASE = problem_type["title"] SCREAMING_SNAKE_CASE = problem_type["num_labels"] SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) SCREAMING_SNAKE_CASE = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=__lowerCamelCase ) as warning_list: SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def _snake_case ( self : List[Any] ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = LevitModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Dict ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([1.0_448, -0.3_745, -1.8_317] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
698
0
from __future__ import annotations from collections.abc import Generator def __a ( ): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = 2 while True: SCREAMING_SNAKE_CASE = factor_map.pop(A__ , A__ ) if factor: SCREAMING_SNAKE_CASE = factor + prime while x in factor_map: x += factor SCREAMING_SNAKE_CASE = factor else: SCREAMING_SNAKE_CASE = prime yield prime prime += 1 def __a ( A__ : float = 1E1_0 ): SCREAMING_SNAKE_CASE = sieve() SCREAMING_SNAKE_CASE = 1 while True: SCREAMING_SNAKE_CASE = next(A__ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(A__ ) n += 2 if __name__ == "__main__": print(solution())
709
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): return None class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : int ): return None class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = [ # (model_name, model_kwargs) ("bert-base-cased", {}), ("gpt2", {"use_cache": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : Optional[int] ): from transformers import BertModel SCREAMING_SNAKE_CASE = ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"] with NamedTemporaryFile(mode="w+t" ) as vocab_file: vocab_file.write("\n".join(__lowerCamelCase ) ) vocab_file.flush() SCREAMING_SNAKE_CASE = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: SCREAMING_SNAKE_CASE = BertModel(BertConfig(vocab_size=len(__lowerCamelCase ) ) ) model.save_pretrained(__lowerCamelCase ) self._test_export(__lowerCamelCase , "pt" , 12 , __lowerCamelCase ) @require_tf @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(Path(__lowerCamelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) @require_torch @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(__lowerCamelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) def _snake_case ( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Tuple=None , **__lowerCamelCase : List[str] ): try: # Compute path with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE = Path(__lowerCamelCase ).joinpath("model.onnx" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) return path except Exception as e: self.fail(__lowerCamelCase ) @require_torch @require_tokenizers @slow def _snake_case ( self : Dict ): from transformers import BertModel SCREAMING_SNAKE_CASE = BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "pt" ) @require_tf @require_tokenizers @slow def _snake_case ( self : int ): from transformers import TFBertModel SCREAMING_SNAKE_CASE = TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "tf" ) def _snake_case ( self : int , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = FeatureExtractionPipeline(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = infer_shapes(__lowerCamelCase , __lowerCamelCase ) # Assert all variables are present self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __lowerCamelCase ) self.assertSequenceEqual(variable_names[3:] , __lowerCamelCase ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: "batch", 1: "sequence"} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["output_0"] , {0: "batch", 1: "sequence"} ) self.assertDictEqual(shapes["output_1"] , {0: "batch"} ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask", "token_type_ids"] SCREAMING_SNAKE_CASE = {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__lowerCamelCase ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__lowerCamelCase ) , set(__lowerCamelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__lowerCamelCase , (tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncNonContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__lowerCamelCase ) , 1 ) self.assertEqual(len(__lowerCamelCase ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["input_ids"] ) self.assertEqual(ordered_input_names[0] , "input_ids" ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = generate_identified_filename(Path("/home/something/my_fake_model.onnx" ) , "-test" ) self.assertEqual("/home/something/my_fake_model-test.onnx" , generated.as_posix() )
698
0
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask __A : int = logging.getLogger(__name__) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "token-classification" def __init__( self : Dict , __lowerCamelCase : List[Any] ): if type(__lowerCamelCase ) == dict: SCREAMING_SNAKE_CASE = Namespace(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = import_module("tasks" ) try: SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , hparams.task_type ) SCREAMING_SNAKE_CASE = token_classification_task_clazz() except AttributeError: raise ValueError( f"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) SCREAMING_SNAKE_CASE = self.token_classification_task.get_labels(hparams.labels ) SCREAMING_SNAKE_CASE = CrossEntropyLoss().ignore_index super().__init__(__lowerCamelCase , len(self.labels ) , self.mode ) def _snake_case ( self : List[Any] , **__lowerCamelCase : Any ): return self.model(**__lowerCamelCase ) def _snake_case ( self : int , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE = self(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = self.hparams for mode in ["train", "dev", "test"]: SCREAMING_SNAKE_CASE = self._feature_file(__lowerCamelCase ) if os.path.exists(__lowerCamelCase ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) SCREAMING_SNAKE_CASE = self.token_classification_task.read_examples_from_file(args.data_dir , __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.token_classification_task.convert_examples_to_features( __lowerCamelCase , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["xlnet"] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["xlnet"] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=__lowerCamelCase , pad_on_left=bool(self.config.model_type in ["xlnet"] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("Saving features into cached file %s" , __lowerCamelCase ) torch.save(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : bool = False ): SCREAMING_SNAKE_CASE = self._feature_file(__lowerCamelCase ) logger.info("Loading features from cached file %s" , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: SCREAMING_SNAKE_CASE = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: SCREAMING_SNAKE_CASE = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) SCREAMING_SNAKE_CASE = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , batch_size=__lowerCamelCase ) def _snake_case ( self : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Any ): """Compute validation""" "" SCREAMING_SNAKE_CASE = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE = self(**__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = outputs[:2] SCREAMING_SNAKE_CASE = logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _snake_case ( self : Dict , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = torch.stack([x["val_loss"] for x in outputs] ).mean() SCREAMING_SNAKE_CASE = np.concatenate([x["pred"] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE = np.argmax(__lowerCamelCase , axis=2 ) SCREAMING_SNAKE_CASE = np.concatenate([x["target"] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE = dict(enumerate(self.labels ) ) SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) SCREAMING_SNAKE_CASE = { "val_loss": val_loss_mean, "accuracy_score": accuracy_score(__lowerCamelCase , __lowerCamelCase ), "precision": precision_score(__lowerCamelCase , __lowerCamelCase ), "recall": recall_score(__lowerCamelCase , __lowerCamelCase ), "f1": fa_score(__lowerCamelCase , __lowerCamelCase ), } SCREAMING_SNAKE_CASE = dict(results.items() ) SCREAMING_SNAKE_CASE = results return ret, preds_list, out_label_list def _snake_case ( self : List[str] , __lowerCamelCase : int ): # when stable SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._eval_end(__lowerCamelCase ) SCREAMING_SNAKE_CASE = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _snake_case ( self : List[Any] , __lowerCamelCase : Tuple ): # updating to test_epoch_end instead of deprecated test_end SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._eval_end(__lowerCamelCase ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 SCREAMING_SNAKE_CASE = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _snake_case ( __lowerCamelCase : List[str] , __lowerCamelCase : str ): # Add NER specific options BaseTransformer.add_model_specific_args(__lowerCamelCase , __lowerCamelCase ) parser.add_argument( "--task_type" , default="NER" , type=__lowerCamelCase , help="Task type to fine tune in training (e.g. NER, POS, etc)" ) parser.add_argument( "--max_seq_length" , default=128 , type=__lowerCamelCase , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--labels" , default="" , type=__lowerCamelCase , help="Path to a file containing all labels. If not specified, CoNLL-2003 labels are used." , ) parser.add_argument( "--gpus" , default=0 , type=__lowerCamelCase , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) __A : Union[str, Any] = NERTransformer.add_model_specific_args(parser, os.getcwd()) __A : Optional[Any] = parser.parse_args() __A : Optional[int] = NERTransformer(args) __A : int = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 __A : Union[str, Any] = sorted(glob.glob(os.path.join(args.output_dir, 'checkpoint-epoch=*.ckpt'), recursive=True)) __A : Union[str, Any] = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
710
from manim import * class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("CPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("GPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Model" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): rect.set_stroke(__lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__lowerCamelCase , buff=0.0 ) self.add(__lowerCamelCase ) cpu_targs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Loaded Checkpoint" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , aligned_edge=__lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) SCREAMING_SNAKE_CASE = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = MarkupText( f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(__lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) SCREAMING_SNAKE_CASE = MarkupText( f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__lowerCamelCase ) , Write(__lowerCamelCase ) ) self.play(Write(__lowerCamelCase , run_time=1 ) , Create(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): SCREAMING_SNAKE_CASE = fill.copy().set_fill(__lowerCamelCase , opacity=0.7 ) target.move_to(__lowerCamelCase ) first_animations.append(GrowFromCenter(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__lowerCamelCase , run_time=1.5 ) ) self.play(*__lowerCamelCase ) self.play(*__lowerCamelCase ) self.wait()
698
0
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, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Union[str, Any] ): pass def __a ( A__ : str ): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A : Tuple = ( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def _snake_case ( self : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model=__lowerCamelCase , tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) SCREAMING_SNAKE_CASE = "What is the placebo?" SCREAMING_SNAKE_CASE = [ { "image": load_image(__lowerCamelCase ), "question": question, }, { "image": image, "question": question, }, { "image": image, "question": question, "word_boxes": word_boxes, }, ] return dqa_pipeline, examples def _snake_case ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = dqa_pipeline(__lowerCamelCase , top_k=2 ) self.assertEqual( __lowerCamelCase , [ [ {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = pipeline("document-question-answering" , model="hf-internal-testing/tiny-random-layoutlmv2" ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "How many cats are there?" SCREAMING_SNAKE_CASE = [ {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) # We can optionnally pass directly the words and bounding boxes SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , words=__lowerCamelCase , boxes=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) @slow @require_torch def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="naver-clova-ix/donut-base-finetuned-docvqa" , tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa" ) , feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , [{"answer": "us-001"}] ) @require_tf @unittest.skip("Document question answering not implemented in TF" ) def _snake_case ( self : List[Any] ): pass
711
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 import ANY if is_vision_available(): from PIL import Image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Any , **__lowerCamelCase : Any ): pass @is_pipeline_test @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @require_torch def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowerCamelCase ) , [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @require_tf def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @slow @require_torch def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , )
698
0
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 PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : Optional[Any] = '▁' __A : Dict = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } __A : List[str] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } __A : Optional[Any] = { 'facebook/s2t-small-librispeech-asr': 1_0_2_4, } __A : str = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] __A : Optional[Any] = {'mustc': MUSTC_LANGS} class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = MAX_MODEL_INPUT_SIZES lowerCamelCase__ = ["input_ids", "attention_mask"] lowerCamelCase__ = [] def __init__( self : Any , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str]="<s>" , __lowerCamelCase : List[Any]="</s>" , __lowerCamelCase : Optional[int]="<pad>" , __lowerCamelCase : List[Any]="<unk>" , __lowerCamelCase : List[str]=False , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : Any=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Optional[Dict[str, Any]] = None , **__lowerCamelCase : Dict , ): SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , pad_token=__lowerCamelCase , do_upper_case=__lowerCamelCase , do_lower_case=__lowerCamelCase , tgt_lang=__lowerCamelCase , lang_codes=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) SCREAMING_SNAKE_CASE = do_upper_case SCREAMING_SNAKE_CASE = do_lower_case SCREAMING_SNAKE_CASE = load_json(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE = spm_file SCREAMING_SNAKE_CASE = load_spm(__lowerCamelCase , self.sp_model_kwargs ) if lang_codes is not None: SCREAMING_SNAKE_CASE = lang_codes SCREAMING_SNAKE_CASE = LANGUAGES[lang_codes] SCREAMING_SNAKE_CASE = [f"<lang:{lang}>" for lang in self.langs] SCREAMING_SNAKE_CASE = {lang: self.sp_model.PieceToId(f"<lang:{lang}>" ) for lang in self.langs} SCREAMING_SNAKE_CASE = self.lang_tokens SCREAMING_SNAKE_CASE = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: SCREAMING_SNAKE_CASE = {} @property def _snake_case ( self : Union[str, Any] ): return len(self.encoder ) @property def _snake_case ( self : List[str] ): return self._tgt_lang @tgt_lang.setter def _snake_case ( self : Tuple , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = new_tgt_lang self.set_tgt_lang_special_tokens(__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = self.lang_code_to_id[tgt_lang] SCREAMING_SNAKE_CASE = [lang_code_id] def _snake_case ( self : List[Any] , __lowerCamelCase : str ): return self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) def _snake_case ( self : Dict , __lowerCamelCase : Tuple ): return self.encoder.get(__lowerCamelCase , self.encoder[self.unk_token] ) def _snake_case ( self : Dict , __lowerCamelCase : int ): return self.decoder.get(__lowerCamelCase , self.unk_token ) def _snake_case ( self : Dict , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: SCREAMING_SNAKE_CASE = self.sp_model.decode(__lowerCamelCase ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " SCREAMING_SNAKE_CASE = [] else: current_sub_tokens.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.sp_model.decode(__lowerCamelCase ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def _snake_case ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Dict=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id] def _snake_case ( self : List[Any] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__lowerCamelCase )) + suffix_ones return prefix_ones + ([0] * len(__lowerCamelCase )) + ([0] * len(__lowerCamelCase )) + suffix_ones def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.__dict__.copy() SCREAMING_SNAKE_CASE = None return state def __setstate__( self : str , __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): SCREAMING_SNAKE_CASE = Path(__lowerCamelCase ) assert save_dir.is_dir(), f"{save_directory} should be a directory" SCREAMING_SNAKE_CASE = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) SCREAMING_SNAKE_CASE = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __lowerCamelCase ) if os.path.abspath(self.spm_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __lowerCamelCase ) elif not os.path.isfile(self.spm_file ): with open(__lowerCamelCase , "wb" ) as fi: SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (str(__lowerCamelCase ), str(__lowerCamelCase )) def __a ( A__ : str , A__ : Dict[str, Any] ): SCREAMING_SNAKE_CASE = sentencepiece.SentencePieceProcessor(**A__ ) spm.Load(str(A__ ) ) return spm def __a ( A__ : str ): with open(A__ , "r" ) as f: return json.load(A__ ) def __a ( A__ : Dict , A__ : str ): with open(A__ , "w" ) as f: json.dump(A__ , A__ , indent=2 )
712
__A : dict[str, float] = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.6_0217_6634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def __a ( A__ : str , A__ : str , A__ : float ): if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: SCREAMING_SNAKE_CASE = ( F"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" F"Valid values are: {', '.join(A__ )}" ) raise ValueError(A__ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
698
0
'''simple docstring''' import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : Dict , __lowerCamelCase : NestedDataStructureLike[PathLike] , __lowerCamelCase : Optional[NamedSplit] = None , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[str] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : Tuple , ): super().__init__( __lowerCamelCase , split=__lowerCamelCase , features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) SCREAMING_SNAKE_CASE = field SCREAMING_SNAKE_CASE = path_or_paths if isinstance(__lowerCamelCase , __lowerCamelCase ) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE = Json( cache_dir=__lowerCamelCase , data_files=__lowerCamelCase , features=__lowerCamelCase , field=__lowerCamelCase , **__lowerCamelCase , ) def _snake_case ( self : Any ): # Build iterable dataset if self.streaming: SCREAMING_SNAKE_CASE = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE = self.builder.as_dataset( split=self.split , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , __lowerCamelCase : Dataset , __lowerCamelCase : Union[PathLike, BinaryIO] , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : int , ): if num_proc is not None and num_proc <= 0: raise ValueError(f"num_proc {num_proc} must be an integer > 0." ) SCREAMING_SNAKE_CASE = dataset SCREAMING_SNAKE_CASE = path_or_buf SCREAMING_SNAKE_CASE = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE = num_proc SCREAMING_SNAKE_CASE = "utf-8" SCREAMING_SNAKE_CASE = to_json_kwargs def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop("path_or_buf" , __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop("orient" , "records" ) SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop("lines" , True if orient == "records" else False ) SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop("index" , False if orient in ["split", "table"] else True ) SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop("compression" , __lowerCamelCase ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(f"`datasets` currently does not support {compression} compression" ) if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf , "wb" , compression=__lowerCamelCase ) as buffer: SCREAMING_SNAKE_CASE = self._write(file_obj=__lowerCamelCase , orient=__lowerCamelCase , lines=__lowerCamelCase , index=__lowerCamelCase , **self.to_json_kwargs ) else: if compression: raise NotImplementedError( f"The compression parameter is not supported when writing to a buffer, but compression={compression}" " was passed. Please provide a local path instead." ) SCREAMING_SNAKE_CASE = self._write( file_obj=self.path_or_buf , orient=__lowerCamelCase , lines=__lowerCamelCase , index=__lowerCamelCase , **self.to_json_kwargs ) return written def _snake_case ( self : str , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = args SCREAMING_SNAKE_CASE = query_table( table=self.dataset.data , key=slice(__lowerCamelCase , offset + self.batch_size ) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE = batch.to_pandas().to_json( path_or_buf=__lowerCamelCase , orient=__lowerCamelCase , lines=__lowerCamelCase , index=__lowerCamelCase , **__lowerCamelCase ) if not json_str.endswith("\n" ): json_str += "\n" return json_str.encode(self.encoding ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : BinaryIO , __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : int , **__lowerCamelCase : List[str] , ): SCREAMING_SNAKE_CASE = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating json from Arrow format" , ): SCREAMING_SNAKE_CASE = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(__lowerCamelCase ) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , __lowerCamelCase , __lowerCamelCase )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating json from Arrow format" , ): written += file_obj.write(__lowerCamelCase ) return written
713
from collections import deque from .hash_table import HashTable class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : Optional[int] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Optional[Any] ): super().__init__(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : Dict , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.values[key] def _snake_case ( self : Union[str, Any] ): return ( sum(self.charge_factor - len(__lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__lowerCamelCase ) == 0 ): return key return super()._collision_resolution(__lowerCamelCase , __lowerCamelCase )
698
0
__A : Tuple = 'Tobias Carryer' from time import time class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple=int(time() ) ): # noqa: B008 SCREAMING_SNAKE_CASE = multiplier SCREAMING_SNAKE_CASE = increment SCREAMING_SNAKE_CASE = modulo SCREAMING_SNAKE_CASE = seed def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. __A : Any = LinearCongruentialGenerator(1_6_6_4_5_2_5, 1_0_1_3_9_0_4_2_2_3, 2 << 3_1) while True: print(lcg.next_number())
714
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : int = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "gpt_neo" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : str , __lowerCamelCase : Dict=50257 , __lowerCamelCase : Tuple=2048 , __lowerCamelCase : Optional[Any]=2048 , __lowerCamelCase : int=24 , __lowerCamelCase : int=[[["global", "local"], 12]] , __lowerCamelCase : int=16 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]=256 , __lowerCamelCase : Tuple="gelu_new" , __lowerCamelCase : Optional[Any]=0.0 , __lowerCamelCase : str=0.0 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[Any]=1e-5 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Dict=True , __lowerCamelCase : Dict=50256 , __lowerCamelCase : Optional[int]=50256 , **__lowerCamelCase : Dict , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_layers SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = window_size SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_dropout SCREAMING_SNAKE_CASE = embed_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = classifier_dropout SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id SCREAMING_SNAKE_CASE = attention_types SCREAMING_SNAKE_CASE = self.expand_attention_types_params(__lowerCamelCase ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " f"`config.num_layers = {self.num_layers}`. " "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) @staticmethod def _snake_case ( __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __a ( A__ : str , A__ : List[Any] , A__ : List[str] , A__ : Union[str, Any] ): import torch SCREAMING_SNAKE_CASE = input.size() SCREAMING_SNAKE_CASE = len(A__ ) SCREAMING_SNAKE_CASE = shape[dimension] SCREAMING_SNAKE_CASE = torch.arange(0 , A__ , A__ ) SCREAMING_SNAKE_CASE = torch.div(sizedim - size , A__ , rounding_mode="floor" ) + 1 SCREAMING_SNAKE_CASE = torch.arange(A__ ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE = [slice(A__ )] * rank SCREAMING_SNAKE_CASE = indices SCREAMING_SNAKE_CASE = input[s] SCREAMING_SNAKE_CASE = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(A__ ) def __a ( A__ : Union[str, Any] , A__ : Optional[int] ): import torch SCREAMING_SNAKE_CASE = torch.arange(1 , A__ ) SCREAMING_SNAKE_CASE = torch.remainder(A__ , A__ ) SCREAMING_SNAKE_CASE = remainders == 0 SCREAMING_SNAKE_CASE = candidates[divisor_indices] SCREAMING_SNAKE_CASE = torch.max(A__ ) return largest_divisor, torch.div(A__ , A__ , rounding_mode="floor" ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__lowerCamelCase , direction="inputs" ) SCREAMING_SNAKE_CASE = {0: "batch", 1: "past_sequence + sequence"} else: SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return common_inputs @property def _snake_case ( self : Optional[int] ): return self._config.num_heads def _snake_case ( self : Union[str, Any] , __lowerCamelCase : PreTrainedTokenizer , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[TensorType] = None , ): SCREAMING_SNAKE_CASE = super(__lowerCamelCase , self ).generate_dummy_inputs( __lowerCamelCase , batch_size=__lowerCamelCase , seq_length=__lowerCamelCase , is_pair=__lowerCamelCase , framework=__lowerCamelCase ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = common_inputs["input_ids"].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE = seqlen + 2 SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE = [ (torch.zeros(__lowerCamelCase ), torch.zeros(__lowerCamelCase )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE = common_inputs["attention_mask"] if self.use_past: SCREAMING_SNAKE_CASE = ordered_inputs["attention_mask"].dtype SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__lowerCamelCase , __lowerCamelCase , dtype=__lowerCamelCase )] , dim=1 ) return ordered_inputs @property def _snake_case ( self : Optional[int] ): return 13
698
0
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = "hf-internal-testing/tiny-random-t5" SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer("This is me" , return_tensors="pt" ) SCREAMING_SNAKE_CASE = model.to_bettertransformer() self.assertTrue(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) SCREAMING_SNAKE_CASE = model.generate(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.reverse_bettertransformer() self.assertFalse(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(__lowerCamelCase ) self.assertFalse( any("BetterTransformer" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) SCREAMING_SNAKE_CASE = model_reloaded.generate(**__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , __lowerCamelCase ) ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = "hf-internal-testing/tiny-random-t5" SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowerCamelCase ): model.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.reverse_bettertransformer() model.save_pretrained(__lowerCamelCase )
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __A : Any = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Union[str, Any] = { 'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "roc_bert" def __init__( self : List[str] , __lowerCamelCase : Any=30522 , __lowerCamelCase : Union[str, Any]=768 , __lowerCamelCase : int=12 , __lowerCamelCase : int=12 , __lowerCamelCase : Any=3072 , __lowerCamelCase : Any="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Dict=512 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : int=1e-12 , __lowerCamelCase : str=True , __lowerCamelCase : List[Any]=0 , __lowerCamelCase : str="absolute" , __lowerCamelCase : Dict=None , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : List[str]=768 , __lowerCamelCase : Any=910 , __lowerCamelCase : Union[str, Any]=512 , __lowerCamelCase : Dict=24858 , __lowerCamelCase : Tuple=True , **__lowerCamelCase : Any , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = enable_pronunciation SCREAMING_SNAKE_CASE = enable_shape SCREAMING_SNAKE_CASE = pronunciation_embed_dim SCREAMING_SNAKE_CASE = pronunciation_vocab_size SCREAMING_SNAKE_CASE = shape_embed_dim SCREAMING_SNAKE_CASE = shape_vocab_size SCREAMING_SNAKE_CASE = concat_input SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = classifier_dropout super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase )
716
import cmath import math def __a ( A__ : float , A__ : float , A__ : float , A__ : float ): SCREAMING_SNAKE_CASE = math.radians(A__ ) SCREAMING_SNAKE_CASE = math.radians(A__ ) # Convert voltage and current to rectangular form SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
698
0
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 _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = 4_2 lowerCamelCase__ = 4_2 def __init__( self : List[Any] , __lowerCamelCase : UNetaDModel , __lowerCamelCase : ScoreSdeVeScheduler ): super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) @torch.no_grad() def __call__( self : str , __lowerCamelCase : int = 1 , __lowerCamelCase : int = 2000 , __lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __lowerCamelCase : Optional[str] = "pil" , __lowerCamelCase : bool = True , **__lowerCamelCase : List[Any] , ): SCREAMING_SNAKE_CASE = self.unet.config.sample_size SCREAMING_SNAKE_CASE = (batch_size, 3, img_size, img_size) SCREAMING_SNAKE_CASE = self.unet SCREAMING_SNAKE_CASE = randn_tensor(__lowerCamelCase , generator=__lowerCamelCase ) * self.scheduler.init_noise_sigma SCREAMING_SNAKE_CASE = sample.to(self.device ) self.scheduler.set_timesteps(__lowerCamelCase ) self.scheduler.set_sigmas(__lowerCamelCase ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): SCREAMING_SNAKE_CASE = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): SCREAMING_SNAKE_CASE = self.unet(__lowerCamelCase , __lowerCamelCase ).sample SCREAMING_SNAKE_CASE = self.scheduler.step_correct(__lowerCamelCase , __lowerCamelCase , generator=__lowerCamelCase ).prev_sample # prediction step SCREAMING_SNAKE_CASE = model(__lowerCamelCase , __lowerCamelCase ).sample SCREAMING_SNAKE_CASE = self.scheduler.step_pred(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , generator=__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = output.prev_sample, output.prev_sample_mean SCREAMING_SNAKE_CASE = sample_mean.clamp(0 , 1 ) SCREAMING_SNAKE_CASE = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE = self.numpy_to_pil(__lowerCamelCase ) if not return_dict: return (sample,) return ImagePipelineOutput(images=__lowerCamelCase )
717
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(A__ , A__ ) def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(A__ , A__ , bias=A__ ) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def __a ( A__ : Tuple , A__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = {} for old_key in state_dict.keys(): SCREAMING_SNAKE_CASE = old_key if "moe_layer.experts." in key: if expert_idx is not None: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts.0" , F"ffn.experts.expert_{expert_idx}" ) else: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: SCREAMING_SNAKE_CASE = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: SCREAMING_SNAKE_CASE = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("final_layer_norm" , "ff_layer_norm" ) SCREAMING_SNAKE_CASE = state_dict[old_key] return new_dict def __a ( A__ : List[str] , A__ : List[Any] , A__ : str , A__ : Union[str, Any] , A__ : str = WEIGHTS_NAME ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 os.makedirs(A__ , exist_ok=A__ ) for expert in range(A__ ): SCREAMING_SNAKE_CASE = switch_checkpoint_path + F"-rank-{expert}.pt" if os.path.isfile(A__ ): SCREAMING_SNAKE_CASE = torch.load(A__ )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = os.path.join( A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) torch.save(A__ , A__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A__ )[0]].dtype ) # Add the last block SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) SCREAMING_SNAKE_CASE = torch.load(switch_checkpoint_path + "-shared.pt" )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A__ ) == 1: SCREAMING_SNAKE_CASE = os.path.join(A__ , A__ ) torch.save(A__ , A__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A__ , A__ ) # Otherwise, let's build the index SCREAMING_SNAKE_CASE = {} for idx, shard in enumerate(A__ ): SCREAMING_SNAKE_CASE = weights_name.replace(".bin" , F"-{idx+1:05d}-of-{len(A__ ):05d}.bin" ) SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(A__ , os.path.join(A__ , A__ ) ) for key in shard: SCREAMING_SNAKE_CASE = shard_file # Add the metadata SCREAMING_SNAKE_CASE = {"total_size": total_size} SCREAMING_SNAKE_CASE = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(A__ , A__ ) , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE = json.dumps(A__ , indent=2 , sort_keys=A__ ) + "\n" f.write(A__ ) return metadata, index if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) __A : Optional[int] = parser.parse_args() __A , __A : Union[str, Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_2_8, args.dtype, ) __A : Any = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8 ) config.save_pretrained(args.pytorch_dump_folder_path) __A : Any = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
698
0
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 _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : List[Any] , __lowerCamelCase : List[str]=1 , __lowerCamelCase : Dict=0 , __lowerCamelCase : int=2 , __lowerCamelCase : Optional[int]=512 , __lowerCamelCase : Optional[Any]="cls" , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : Tuple=True , **__lowerCamelCase : List[Any] , ): super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = project_dim SCREAMING_SNAKE_CASE = pooler_fn SCREAMING_SNAKE_CASE = learn_encoder SCREAMING_SNAKE_CASE = use_attention_mask class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = [R"pooler", R"logit_scale"] lowerCamelCase__ = [R"position_ids", R"predictions.decoder.bias"] lowerCamelCase__ = "roberta" lowerCamelCase__ = RobertaSeriesConfig def __init__( self : Union[str, Any] , __lowerCamelCase : Tuple ): super().__init__(__lowerCamelCase ) SCREAMING_SNAKE_CASE = XLMRobertaModel(__lowerCamelCase ) SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , "has_pre_transformation" , __lowerCamelCase ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def _snake_case ( self : Any , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[bool] = None , ): SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE = self.base_model( input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase , position_ids=__lowerCamelCase , head_mask=__lowerCamelCase , inputs_embeds=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , output_attentions=__lowerCamelCase , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__lowerCamelCase , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE = outputs["hidden_states"][-2] SCREAMING_SNAKE_CASE = self.pre_LN(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.transformation_pre(__lowerCamelCase ) return TransformationModelOutput( projection_state=__lowerCamelCase , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__lowerCamelCase , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
718
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = BlipImageProcessor() SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" ) SCREAMING_SNAKE_CASE = BlipProcessor(__lowerCamelCase , __lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self : Dict , **__lowerCamelCase : Any ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).tokenizer def _snake_case ( self : List[Any] , **__lowerCamelCase : Optional[Any] ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).image_processor def _snake_case ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__lowerCamelCase , padding_value=1.0 ) SCREAMING_SNAKE_CASE = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCamelCase ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = image_processor(__lowerCamelCase , return_tensors="np" ) SCREAMING_SNAKE_CASE = processor(images=__lowerCamelCase , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
698
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 __A : Dict = get_tests_dir('fixtures') class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE = mock.Mock() SCREAMING_SNAKE_CASE = 500 SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = HTTPError SCREAMING_SNAKE_CASE = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=__lowerCamelCase ) as mock_head: SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json" ) @is_staging_test class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @classmethod def _snake_case ( cls : Optional[int] ): SCREAMING_SNAKE_CASE = TOKEN HfFolder.save_token(__lowerCamelCase ) @classmethod def _snake_case ( cls : List[str] ): try: delete_repo(token=cls._token , repo_id="test-feature-extractor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-feature-extractor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-feature-extractor" ) except HTTPError: pass def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(__lowerCamelCase ) feature_extractor.push_to_hub("test-feature-extractor" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__lowerCamelCase , getattr(__lowerCamelCase , __lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-feature-extractor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( __lowerCamelCase , repo_id="test-feature-extractor" , push_to_hub=__lowerCamelCase , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__lowerCamelCase , getattr(__lowerCamelCase , __lowerCamelCase ) ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(__lowerCamelCase ) feature_extractor.push_to_hub("valid_org/test-feature-extractor" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__lowerCamelCase , getattr(__lowerCamelCase , __lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-feature-extractor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( __lowerCamelCase , repo_id="valid_org/test-feature-extractor-org" , push_to_hub=__lowerCamelCase , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__lowerCamelCase , getattr(__lowerCamelCase , __lowerCamelCase ) ) def _snake_case ( self : Optional[Any] ): CustomFeatureExtractor.register_for_auto_class() SCREAMING_SNAKE_CASE = CustomFeatureExtractor.from_pretrained(__lowerCamelCase ) feature_extractor.push_to_hub("test-dynamic-feature-extractor" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"} , ) SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( f"{USER}/test-dynamic-feature-extractor" , trust_remote_code=__lowerCamelCase ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , "CustomFeatureExtractor" )
719
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, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Union[str, Any] ): pass def __a ( A__ : str ): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A : Tuple = ( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def _snake_case ( self : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model=__lowerCamelCase , tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) SCREAMING_SNAKE_CASE = "What is the placebo?" SCREAMING_SNAKE_CASE = [ { "image": load_image(__lowerCamelCase ), "question": question, }, { "image": image, "question": question, }, { "image": image, "question": question, "word_boxes": word_boxes, }, ] return dqa_pipeline, examples def _snake_case ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = dqa_pipeline(__lowerCamelCase , top_k=2 ) self.assertEqual( __lowerCamelCase , [ [ {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = pipeline("document-question-answering" , model="hf-internal-testing/tiny-random-layoutlmv2" ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "How many cats are there?" SCREAMING_SNAKE_CASE = [ {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) # We can optionnally pass directly the words and bounding boxes SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , words=__lowerCamelCase , boxes=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) @slow @require_torch def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="naver-clova-ix/donut-base-finetuned-docvqa" , tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa" ) , feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , [{"answer": "us-001"}] ) @require_tf @unittest.skip("Document question answering not implemented in TF" ) def _snake_case ( self : List[Any] ): pass
698
0
import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def __a ( A__ : List[str] , A__ : Dict=False ): SCREAMING_SNAKE_CASE = OmegaConf.load(A__ ) if display: print(yaml.dump(OmegaConf.to_container(A__ ) ) ) return config def __a ( A__ : List[Any] , A__ : int=None , A__ : Dict=None ): if conf_path is None: SCREAMING_SNAKE_CASE = "./model_checkpoints/vqgan_only.yaml" SCREAMING_SNAKE_CASE = load_config(A__ , display=A__ ) SCREAMING_SNAKE_CASE = VQModel(**config.model.params ) if ckpt_path is None: SCREAMING_SNAKE_CASE = "./model_checkpoints/vqgan_only.pt" SCREAMING_SNAKE_CASE = torch.load(A__ , map_location=A__ ) if ".ckpt" in ckpt_path: SCREAMING_SNAKE_CASE = sd["state_dict"] model.load_state_dict(A__ , strict=A__ ) model.to(A__ ) del sd return model def __a ( A__ : Dict , A__ : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model.encode(A__ ) print(F"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) SCREAMING_SNAKE_CASE = model.decode(A__ ) return xrec def __a ( A__ : str , A__ : Optional[int]=False ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = string.rsplit("." , 1 ) if reload: SCREAMING_SNAKE_CASE = importlib.import_module(A__ ) importlib.reload(A__ ) return getattr(importlib.import_module(A__ , package=A__ ) , cls ) def __a ( A__ : Dict ): if "target" not in config: raise KeyError("Expected key `target` to instantiate." ) return get_obj_from_str(config["target"] )(**config.get("params" , {} ) ) def __a ( A__ : Dict , A__ : List[str] , A__ : Dict=True , A__ : Optional[Any]=True ): SCREAMING_SNAKE_CASE = instantiate_from_config(A__ ) if sd is not None: model.load_state_dict(A__ ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def __a ( A__ : List[Any] , A__ : Optional[int] , A__ : List[str] , A__ : Optional[int] ): # load the specified checkpoint if ckpt: SCREAMING_SNAKE_CASE = torch.load(A__ , map_location="cpu" ) SCREAMING_SNAKE_CASE = pl_sd["global_step"] print(F"loaded model from global step {global_step}." ) else: SCREAMING_SNAKE_CASE = {"state_dict": None} SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = load_model_from_config(config.model , pl_sd["state_dict"] , gpu=A__ , eval_mode=A__ )["model"] return model, global_step
720
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "facebook/bart-large-mnli" lowerCamelCase__ = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) lowerCamelCase__ = "text_classifier" lowerCamelCase__ = AutoTokenizer lowerCamelCase__ = AutoModelForSequenceClassification lowerCamelCase__ = ["text", ["text"]] lowerCamelCase__ = ["text"] def _snake_case ( self : Optional[Any] ): super().setup() SCREAMING_SNAKE_CASE = self.model.config SCREAMING_SNAKE_CASE = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): SCREAMING_SNAKE_CASE = int(__lowerCamelCase ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def _snake_case ( self : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = labels return self.pre_processor( [text] * len(__lowerCamelCase ) , [f"This example is {label}" for label in labels] , return_tensors="pt" , padding="max_length" , ) def _snake_case ( self : str , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = outputs.logits SCREAMING_SNAKE_CASE = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
698
0
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) __A : Optional[int] = logging.getLogger(__name__) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Any , __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : Tuple=None ): SCREAMING_SNAKE_CASE = self.layer[current_layer](__lowerCamelCase , __lowerCamelCase , head_mask[current_layer] ) SCREAMING_SNAKE_CASE = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." , __snake_case , ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : str , __lowerCamelCase : Any ): super().__init__(__lowerCamelCase ) SCREAMING_SNAKE_CASE = BertEncoderWithPabee(__lowerCamelCase ) self.init_weights() SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 def _snake_case ( self : List[Any] , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = threshold def _snake_case ( self : Tuple , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = patience def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.inference_layers_num / self.inference_instances_num SCREAMING_SNAKE_CASE = ( f"*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =" f" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***" ) print(__lowerCamelCase ) @add_start_docstrings_to_model_forward(__lowerCamelCase ) def _snake_case ( self : List[str] , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : int=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : int=False , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: SCREAMING_SNAKE_CASE = input_ids.size() elif inputs_embeds is not None: SCREAMING_SNAKE_CASE = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds" ) SCREAMING_SNAKE_CASE = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: SCREAMING_SNAKE_CASE = torch.ones(__lowerCamelCase , device=__lowerCamelCase ) if token_type_ids is None: SCREAMING_SNAKE_CASE = torch.zeros(__lowerCamelCase , dtype=torch.long , device=__lowerCamelCase ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. SCREAMING_SNAKE_CASE = self.get_extended_attention_mask(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = encoder_hidden_states.size() SCREAMING_SNAKE_CASE = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: SCREAMING_SNAKE_CASE = torch.ones(__lowerCamelCase , device=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.invert_attention_mask(__lowerCamelCase ) else: SCREAMING_SNAKE_CASE = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] SCREAMING_SNAKE_CASE = self.get_head_mask(__lowerCamelCase , self.config.num_hidden_layers ) SCREAMING_SNAKE_CASE = self.embeddings( input_ids=__lowerCamelCase , position_ids=__lowerCamelCase , token_type_ids=__lowerCamelCase , inputs_embeds=__lowerCamelCase ) SCREAMING_SNAKE_CASE = embedding_output if self.training: SCREAMING_SNAKE_CASE = [] for i in range(self.config.num_hidden_layers ): SCREAMING_SNAKE_CASE = self.encoder.adaptive_forward( __lowerCamelCase , current_layer=__lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.pooler(__lowerCamelCase ) SCREAMING_SNAKE_CASE = output_layers[i](output_dropout(__lowerCamelCase ) ) res.append(__lowerCamelCase ) elif self.patience == 0: # Use all layers for inference SCREAMING_SNAKE_CASE = self.encoder( __lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = self.pooler(encoder_outputs[0] ) SCREAMING_SNAKE_CASE = [output_layers[self.config.num_hidden_layers - 1](__lowerCamelCase )] else: SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 SCREAMING_SNAKE_CASE = self.encoder.adaptive_forward( __lowerCamelCase , current_layer=__lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.pooler(__lowerCamelCase ) SCREAMING_SNAKE_CASE = output_layers[i](__lowerCamelCase ) if regression: SCREAMING_SNAKE_CASE = logits.detach() if patient_result is not None: SCREAMING_SNAKE_CASE = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: SCREAMING_SNAKE_CASE = 0 else: SCREAMING_SNAKE_CASE = logits.detach().argmax(dim=1 ) if patient_result is not None: SCREAMING_SNAKE_CASE = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(__lowerCamelCase ) ): patient_counter += 1 else: SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = logits if patient_counter == self.patience: break SCREAMING_SNAKE_CASE = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " , __snake_case , ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : List[Any] , __lowerCamelCase : Any ): super().__init__(__lowerCamelCase ) SCREAMING_SNAKE_CASE = config.num_labels SCREAMING_SNAKE_CASE = BertModelWithPabee(__lowerCamelCase ) SCREAMING_SNAKE_CASE = nn.Dropout(config.hidden_dropout_prob ) SCREAMING_SNAKE_CASE = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : int=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : str=None , ): SCREAMING_SNAKE_CASE = self.bert( input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase , position_ids=__lowerCamelCase , head_mask=__lowerCamelCase , inputs_embeds=__lowerCamelCase , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) SCREAMING_SNAKE_CASE = (logits[-1],) if labels is not None: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 for ix, logits_item in enumerate(__lowerCamelCase ): if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE = MSELoss() SCREAMING_SNAKE_CASE = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: SCREAMING_SNAKE_CASE = CrossEntropyLoss() SCREAMING_SNAKE_CASE = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: SCREAMING_SNAKE_CASE = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 SCREAMING_SNAKE_CASE = (total_loss / total_weights,) + outputs return outputs
721
# 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 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __a ( A__ : str=None ): if subparsers is not None: SCREAMING_SNAKE_CASE = subparsers.add_parser("test" ) else: SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=A__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=A__ ) return parser def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: SCREAMING_SNAKE_CASE = script_name else: SCREAMING_SNAKE_CASE = F"--config_file={args.config_file} {script_name}" SCREAMING_SNAKE_CASE = ["accelerate-launch"] + test_args.split() SCREAMING_SNAKE_CASE = execute_subprocess_async(A__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __a ( ): SCREAMING_SNAKE_CASE = test_command_parser() SCREAMING_SNAKE_CASE = parser.parse_args() test_command(A__ ) if __name__ == "__main__": main()
698
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[Any] = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "timm_backbone" def __init__( self : List[str] , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Any=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : List[str]=None , **__lowerCamelCase : Tuple , ): super().__init__(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = features_only SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = out_indices if out_indices is not None else (-1,)
700
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A : Optional[int] = logging.get_logger(__name__) __A : List[str] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } __A : Tuple = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } __A : Dict = {'facebook/blenderbot-3B': 1_2_8} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __a ( ): SCREAMING_SNAKE_CASE = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) SCREAMING_SNAKE_CASE = bs[:] SCREAMING_SNAKE_CASE = 0 for b in range(2**8 ): if b not in bs: bs.append(A__ ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE = [chr(A__ ) for n in cs] return dict(zip(A__ , A__ ) ) def __a ( A__ : Optional[int] ): SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE = char return pairs class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ["input_ids", "attention_mask"] def __init__( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any]="replace" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : List[Any]="</s>" , __lowerCamelCase : Dict="</s>" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : Optional[Any]="<unk>" , __lowerCamelCase : str="<pad>" , __lowerCamelCase : List[Any]="<mask>" , __lowerCamelCase : List[Any]=False , **__lowerCamelCase : Tuple , ): SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else bos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else eos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else sep_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else cls_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else unk_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token super().__init__( errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , **__lowerCamelCase , ) with open(__lowerCamelCase , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE = json.load(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE = bytes_to_unicode() SCREAMING_SNAKE_CASE = {v: k for k, v in self.byte_encoder.items()} with open(__lowerCamelCase , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _snake_case ( self : Dict ): return len(self.encoder ) def _snake_case ( self : int ): return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self : Tuple , __lowerCamelCase : List[str] ): if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE = min(__lowerCamelCase , key=lambda __lowerCamelCase : self.bpe_ranks.get(__lowerCamelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = bigram SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while i < len(__lowerCamelCase ): try: SCREAMING_SNAKE_CASE = word.index(__lowerCamelCase , __lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE = j if word[i] == first and i < len(__lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = new_word if len(__lowerCamelCase ) == 1: break else: SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = word return word def _snake_case ( self : str , __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for token in re.findall(self.pat , __lowerCamelCase ): SCREAMING_SNAKE_CASE = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCamelCase ).split(" " ) ) return bpe_tokens def _snake_case ( self : List[str] , __lowerCamelCase : str ): return self.encoder.get(__lowerCamelCase , self.encoder.get(self.unk_token ) ) def _snake_case ( self : Optional[int] , __lowerCamelCase : Tuple ): return self.decoder.get(__lowerCamelCase ) def _snake_case ( self : Tuple , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = "".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _snake_case ( self : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): if not os.path.isdir(__lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase ) + "\n" ) SCREAMING_SNAKE_CASE = 0 with open(__lowerCamelCase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE = token_index writer.write(" ".join(__lowerCamelCase ) + "\n" ) index += 1 return vocab_file, merge_file def _snake_case ( self : Tuple , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def _snake_case ( self : str , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : Any , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict=False , **__lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowerCamelCase ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE = " " + text return (text, kwargs) def _snake_case ( self : Dict , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): return token_ids_a + [self.eos_token_id] def _snake_case ( self : Tuple , __lowerCamelCase : "Conversation" ): SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(" " + text ) else: # Generated responses should contain them already. inputs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.encode(__lowerCamelCase ) if len(__lowerCamelCase ) > self.model_max_length: SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens." ) return input_ids
698
0
import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : List[str] = { 'facebook/detr-resnet-50': 'https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json', # See all DETR models at https://huggingface.co/models?filter=detr } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "detr" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[Any] , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : int=100 , __lowerCamelCase : List[str]=6 , __lowerCamelCase : Dict=2048 , __lowerCamelCase : str=8 , __lowerCamelCase : int=6 , __lowerCamelCase : List[str]=2048 , __lowerCamelCase : Tuple=8 , __lowerCamelCase : Any=0.0 , __lowerCamelCase : Optional[int]=0.0 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : List[Any]="relu" , __lowerCamelCase : List[str]=256 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Optional[Any]=0.0 , __lowerCamelCase : Optional[int]=0.0 , __lowerCamelCase : int=0.02 , __lowerCamelCase : List[Any]=1.0 , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : str="sine" , __lowerCamelCase : Union[str, Any]="resnet50" , __lowerCamelCase : Any=True , __lowerCamelCase : List[Any]=False , __lowerCamelCase : Optional[Any]=1 , __lowerCamelCase : Union[str, Any]=5 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Dict=1 , __lowerCamelCase : Tuple=1 , __lowerCamelCase : Tuple=5 , __lowerCamelCase : Any=2 , __lowerCamelCase : Optional[int]=0.1 , **__lowerCamelCase : Optional[int] , ): if backbone_config is not None and use_timm_backbone: raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." ) if not use_timm_backbone: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): SCREAMING_SNAKE_CASE = backbone_config.get("model_type" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE = config_class.from_dict(__lowerCamelCase ) # set timm attributes to None SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None, None, None SCREAMING_SNAKE_CASE = use_timm_backbone SCREAMING_SNAKE_CASE = backbone_config SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_queries SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = init_xavier_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = auxiliary_loss SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = dilation # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = mask_loss_coefficient SCREAMING_SNAKE_CASE = dice_loss_coefficient SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient super().__init__(is_encoder_decoder=__lowerCamelCase , **__lowerCamelCase ) @property def _snake_case ( self : Any ): return self.encoder_attention_heads @property def _snake_case ( self : Tuple ): return self.d_model @classmethod def _snake_case ( cls : Tuple , __lowerCamelCase : PretrainedConfig , **__lowerCamelCase : Any ): return cls(backbone_config=__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = version.parse("1.11" ) @property def _snake_case ( self : Any ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def _snake_case ( self : List[str] ): return 1e-5 @property def _snake_case ( self : Optional[int] ): return 12
701
from __future__ import annotations from cmath import sqrt def __a ( A__ : int , A__ : int , A__ : int ): if a == 0: raise ValueError("Coefficient 'a' must not be zero." ) SCREAMING_SNAKE_CASE = b * b - 4 * a * c SCREAMING_SNAKE_CASE = (-b + sqrt(A__ )) / (2 * a) SCREAMING_SNAKE_CASE = (-b - sqrt(A__ )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def __a ( ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = quadratic_roots(a=5 , b=6 , c=1 ) print(F"The solutions are: {solutiona} and {solutiona}" ) if __name__ == "__main__": main()
698
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Union[str, Any] = { 'Salesforce/blip-vqa-base': 'https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json', 'Salesforce/blip-vqa-capfit-large': ( 'https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-base': ( 'https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-large': ( 'https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json' ), 'Salesforce/blip-itm-base-coco': 'https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json', 'Salesforce/blip-itm-large-coco': 'https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json', 'Salesforce/blip-itm-base-flikr': 'https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json', 'Salesforce/blip-itm-large-flikr': ( 'https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json' ), } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "blip_text_model" def __init__( self : str , __lowerCamelCase : int=30524 , __lowerCamelCase : Any=768 , __lowerCamelCase : Optional[int]=768 , __lowerCamelCase : Dict=3072 , __lowerCamelCase : Tuple=768 , __lowerCamelCase : Optional[Any]=12 , __lowerCamelCase : Any=8 , __lowerCamelCase : Any=512 , __lowerCamelCase : str="gelu" , __lowerCamelCase : Optional[Any]=1e-12 , __lowerCamelCase : Optional[int]=0.0 , __lowerCamelCase : Tuple=0.0 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Optional[int]=30522 , __lowerCamelCase : Dict=2 , __lowerCamelCase : str=0 , __lowerCamelCase : List[Any]=102 , __lowerCamelCase : Dict=True , __lowerCamelCase : Tuple=True , **__lowerCamelCase : Optional[Any] , ): super().__init__( pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , sep_token_id=__lowerCamelCase , **__lowerCamelCase , ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = encoder_hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = is_decoder SCREAMING_SNAKE_CASE = use_cache @classmethod def _snake_case ( cls : Tuple , __lowerCamelCase : Union[str, os.PathLike] , **__lowerCamelCase : Tuple ): cls._set_token_in_kwargs(__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cls.get_config_dict(__lowerCamelCase , **__lowerCamelCase ) # get the text config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": SCREAMING_SNAKE_CASE = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "blip_vision_model" def __init__( self : Dict , __lowerCamelCase : Dict=768 , __lowerCamelCase : Optional[Any]=3072 , __lowerCamelCase : Dict=512 , __lowerCamelCase : List[str]=12 , __lowerCamelCase : Tuple=12 , __lowerCamelCase : int=384 , __lowerCamelCase : Tuple=16 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : Dict=1e-5 , __lowerCamelCase : Tuple=0.0 , __lowerCamelCase : Optional[int]=1e-10 , **__lowerCamelCase : List[str] , ): super().__init__(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def _snake_case ( cls : str , __lowerCamelCase : Union[str, os.PathLike] , **__lowerCamelCase : Any ): cls._set_token_in_kwargs(__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cls.get_config_dict(__lowerCamelCase , **__lowerCamelCase ) # get the vision config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": SCREAMING_SNAKE_CASE = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "blip" lowerCamelCase__ = True def __init__( self : Optional[Any] , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : List[Any]=512 , __lowerCamelCase : Union[str, Any]=2.6_592 , __lowerCamelCase : Optional[Any]=256 , **__lowerCamelCase : Optional[Any] , ): super().__init__(**__lowerCamelCase ) if text_config is None: SCREAMING_SNAKE_CASE = {} logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values." ) if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values." ) SCREAMING_SNAKE_CASE = BlipTextConfig(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = BlipVisionConfig(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.vision_config.hidden_size SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = logit_scale_init_value SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.02 SCREAMING_SNAKE_CASE = image_text_hidden_size @classmethod def _snake_case ( cls : Dict , __lowerCamelCase : BlipTextConfig , __lowerCamelCase : BlipVisionConfig , **__lowerCamelCase : Any ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE = self.text_config.to_dict() SCREAMING_SNAKE_CASE = self.vision_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
702
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_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = greedy_ids[:, input_ids.shape[1] :] SCREAMING_SNAKE_CASE = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_prompt=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("distilgpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = torch.ones((1, 5) , device=__lowerCamelCase ).long() * model.config.bos_token_id with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=1 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token SCREAMING_SNAKE_CASE = cs.out[:-1] # Remove the final "\n" SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase , timeout=0.001 ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text
698
0
import faiss # 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 requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets __A : str = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' __A : Dict = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' __A : Dict = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/krishnap25/mauve" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/krishnap25/mauve"] , reference_urls=[ "https://arxiv.org/abs/2102.01454", "https://github.com/krishnap25/mauve", ] , ) def _snake_case ( self : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : Optional[int]="auto" , __lowerCamelCase : Union[str, Any]=-1 , __lowerCamelCase : Any=0.9 , __lowerCamelCase : int=5 , __lowerCamelCase : List[str]=500 , __lowerCamelCase : Optional[int]="gpt2-large" , __lowerCamelCase : Union[str, Any]=-1 , __lowerCamelCase : List[Any]=1024 , __lowerCamelCase : List[str]=25 , __lowerCamelCase : Tuple=5 , __lowerCamelCase : int=True , __lowerCamelCase : Dict=25 , ): SCREAMING_SNAKE_CASE = compute_mauve( p_text=__lowerCamelCase , q_text=__lowerCamelCase , p_features=__lowerCamelCase , q_features=__lowerCamelCase , p_tokens=__lowerCamelCase , q_tokens=__lowerCamelCase , num_buckets=__lowerCamelCase , pca_max_data=__lowerCamelCase , kmeans_explained_var=__lowerCamelCase , kmeans_num_redo=__lowerCamelCase , kmeans_max_iter=__lowerCamelCase , featurize_model_name=__lowerCamelCase , device_id=__lowerCamelCase , max_text_length=__lowerCamelCase , divergence_curve_discretization_size=__lowerCamelCase , mauve_scaling_factor=__lowerCamelCase , verbose=__lowerCamelCase , seed=__lowerCamelCase , ) return out
703
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Union[str, Any] = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __A : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
from pathlib import Path import numpy as np from PIL import Image def __a ( A__ : np.ndarray ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2_9_8_9 * r + 0.5_8_7_0 * g + 0.1_1_4_0 * b def __a ( A__ : np.ndarray ): return (gray > 127) & (gray <= 255) def __a ( A__ : np.ndarray , A__ : np.ndarray ): SCREAMING_SNAKE_CASE = np.zeros_like(A__ ) SCREAMING_SNAKE_CASE = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE = int(summation > 0 ) return output if __name__ == "__main__": # read original image __A : int = Path(__file__).resolve().parent / 'image_data' / 'lena.jpg' __A : List[str] = np.array(Image.open(lena_path)) # kernel to be applied __A : Optional[Any] = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) __A : str = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image __A : List[Any] = Image.fromarray(output).convert('RGB') pil_img.save('result_dilation.png')
704
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __A : Optional[Any] = datasets.load_iris() __A : Optional[Any] = np.array(data['data']) __A : Optional[int] = np.array(data['target']) __A : Union[str, Any] = data['target_names'] __A , __A , __A , __A : Optional[int] = train_test_split(X, y) def __a ( A__ : Optional[int] , A__ : Dict ): return np.linalg.norm(np.array(A__ ) - np.array(A__ ) ) def __a ( A__ : Optional[Any] , A__ : int , A__ : Dict , A__ : Optional[Any] , A__ : Dict=5 ): SCREAMING_SNAKE_CASE = zip(A__ , A__ ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE = [] for data_point in data: SCREAMING_SNAKE_CASE = euclidean_distance(data_point[0] , A__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE = [i[1] for i in sorted(A__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE = Counter(A__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
698
0
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : List[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = (32, 32) SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__lowerCamelCase ) return image @property def _snake_case ( self : List[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def _snake_case ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def _snake_case ( self : Union[str, Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(__lowerCamelCase ) @property def _snake_case ( self : Any ): def extract(*__lowerCamelCase : str , **__lowerCamelCase : Optional[Any] ): class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[int] ): SCREAMING_SNAKE_CASE = torch.ones([0] ) def _snake_case ( self : Any , __lowerCamelCase : Union[str, Any] ): self.pixel_values.to(__lowerCamelCase ) return self return Out() return extract def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.dummy_cond_unet SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=__lowerCamelCase , set_alpha_to_one=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = self.dummy_vae SCREAMING_SNAKE_CASE = self.dummy_text_encoder SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE = StableDiffusionPipeline( unet=__lowerCamelCase , scheduler=__lowerCamelCase , vae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , safety_checker=__lowerCamelCase , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE = sd_pipe([prompt] , generator=__lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=__lowerCamelCase , )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.dummy_cond_unet SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.dummy_vae SCREAMING_SNAKE_CASE = self.dummy_text_encoder SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE = StableDiffusionPipeline( unet=__lowerCamelCase , scheduler=__lowerCamelCase , vae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , safety_checker=__lowerCamelCase , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE = sd_pipe([prompt] , generator=__lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=__lowerCamelCase , )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=__lowerCamelCase ) assert isinstance(__lowerCamelCase , __lowerCamelCase ) assert isinstance(pipe.scheduler , __lowerCamelCase ) assert pipe.safety_checker is None SCREAMING_SNAKE_CASE = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = StableDiffusionPipeline.from_pretrained(__lowerCamelCase ) # sanity check that the pipeline still works assert pipe.safety_checker is None SCREAMING_SNAKE_CASE = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = self.dummy_cond_unet SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.dummy_vae SCREAMING_SNAKE_CASE = self.dummy_text_encoder SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 SCREAMING_SNAKE_CASE = unet.half() SCREAMING_SNAKE_CASE = vae.half() SCREAMING_SNAKE_CASE = bert.half() # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE = StableDiffusionPipeline( unet=__lowerCamelCase , scheduler=__lowerCamelCase , vae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , safety_checker=__lowerCamelCase , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=__lowerCamelCase ) SCREAMING_SNAKE_CASE = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) SCREAMING_SNAKE_CASE = 4003660346 SCREAMING_SNAKE_CASE = 7 # without safety guidance (sld_guidance_scale = 0) SCREAMING_SNAKE_CASE = torch.manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=__lowerCamelCase , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) SCREAMING_SNAKE_CASE = torch.manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=__lowerCamelCase , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=__lowerCamelCase ) SCREAMING_SNAKE_CASE = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "padme amidala taking a bath artwork, safe for work, no nudity" SCREAMING_SNAKE_CASE = 2734971755 SCREAMING_SNAKE_CASE = 7 SCREAMING_SNAKE_CASE = torch.manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=__lowerCamelCase , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 SCREAMING_SNAKE_CASE = torch.manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=__lowerCamelCase , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) SCREAMING_SNAKE_CASE = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) SCREAMING_SNAKE_CASE = 1044355234 SCREAMING_SNAKE_CASE = 12 SCREAMING_SNAKE_CASE = torch.manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=__lowerCamelCase , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 SCREAMING_SNAKE_CASE = torch.manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , generator=__lowerCamelCase , guidance_scale=__lowerCamelCase , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
705
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 __A : Union[str, Any] = logging.get_logger(__name__) __A : Dict = { 'microsoft/resnet-50': 'https://huggingface.co/microsoft/resnet-50/blob/main/config.json', } class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ): '''simple docstring''' lowerCamelCase__ = "resnet" lowerCamelCase__ = ["basic", "bottleneck"] def __init__( self : Optional[Any] , __lowerCamelCase : int=3 , __lowerCamelCase : Dict=64 , __lowerCamelCase : str=[256, 512, 1024, 2048] , __lowerCamelCase : str=[3, 4, 6, 3] , __lowerCamelCase : Optional[int]="bottleneck" , __lowerCamelCase : int="relu" , __lowerCamelCase : List[str]=False , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : int=None , **__lowerCamelCase : Dict , ): super().__init__(**__lowerCamelCase ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embedding_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = downsample_in_first_stage SCREAMING_SNAKE_CASE = ["stem"] + [f"stage{idx}" for idx in range(1 , len(__lowerCamelCase ) + 1 )] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__lowerCamelCase , out_indices=__lowerCamelCase , stage_names=self.stage_names ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = version.parse("1.11" ) @property def _snake_case ( self : Optional[int] ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _snake_case ( self : Optional[int] ): return 1e-3
698
0
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_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = greedy_ids[:, input_ids.shape[1] :] SCREAMING_SNAKE_CASE = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_prompt=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("distilgpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = torch.ones((1, 5) , device=__lowerCamelCase ).long() * model.config.bos_token_id with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=1 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token SCREAMING_SNAKE_CASE = cs.out[:-1] # Remove the final "\n" SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase , timeout=0.001 ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text
706
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType __A : str = logging.get_logger(__name__) __A : Optional[Any] = { 'openai/imagegpt-small': '', 'openai/imagegpt-medium': '', 'openai/imagegpt-large': '', } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "imagegpt" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , __lowerCamelCase : Any=512 + 1 , __lowerCamelCase : str=32 * 32 , __lowerCamelCase : Any=512 , __lowerCamelCase : Optional[int]=24 , __lowerCamelCase : Tuple=8 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]="quick_gelu" , __lowerCamelCase : int=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=1e-5 , __lowerCamelCase : Optional[Any]=0.02 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : List[Any]=False , __lowerCamelCase : int=False , __lowerCamelCase : int=False , **__lowerCamelCase : Union[str, Any] , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_embd SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = tie_word_embeddings super().__init__(tie_word_embeddings=__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Optional[Any] ): return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ] ) def _snake_case ( self : Optional[int] , __lowerCamelCase : "FeatureExtractionMixin" , __lowerCamelCase : int = 1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 32 , __lowerCamelCase : int = 32 , ): SCREAMING_SNAKE_CASE = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dict(preprocessor(images=__lowerCamelCase , return_tensors=__lowerCamelCase ) ) return inputs
698
0
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __A : Optional[int] = logging.get_logger(__name__) def __a ( A__ : Any ): SCREAMING_SNAKE_CASE = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: SCREAMING_SNAKE_CASE = 128 elif "12-12" in model_name: SCREAMING_SNAKE_CASE = 12 SCREAMING_SNAKE_CASE = 12 elif "14-14" in model_name: SCREAMING_SNAKE_CASE = 14 SCREAMING_SNAKE_CASE = 14 elif "16-16" in model_name: SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 16 else: raise ValueError("Model not supported" ) SCREAMING_SNAKE_CASE = "huggingface/label-files" if "speech-commands" in model_name: SCREAMING_SNAKE_CASE = 35 SCREAMING_SNAKE_CASE = "speech-commands-v2-id2label.json" else: SCREAMING_SNAKE_CASE = 527 SCREAMING_SNAKE_CASE = "audioset-id2label.json" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(A__ , A__ , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE = {int(A__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def __a ( A__ : Optional[Any] ): if "module.v" in name: SCREAMING_SNAKE_CASE = name.replace("module.v" , "audio_spectrogram_transformer" ) if "cls_token" in name: SCREAMING_SNAKE_CASE = name.replace("cls_token" , "embeddings.cls_token" ) if "dist_token" in name: SCREAMING_SNAKE_CASE = name.replace("dist_token" , "embeddings.distillation_token" ) if "pos_embed" in name: SCREAMING_SNAKE_CASE = name.replace("pos_embed" , "embeddings.position_embeddings" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) # transformer blocks if "blocks" in name: SCREAMING_SNAKE_CASE = name.replace("blocks" , "encoder.layer" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("attn" , "attention.self" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("mlp.fc2" , "output.dense" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: SCREAMING_SNAKE_CASE = name.replace("audio_spectrogram_transformer.norm" , "audio_spectrogram_transformer.layernorm" ) # classifier head if "module.mlp_head.0" in name: SCREAMING_SNAKE_CASE = name.replace("module.mlp_head.0" , "classifier.layernorm" ) if "module.mlp_head.1" in name: SCREAMING_SNAKE_CASE = name.replace("module.mlp_head.1" , "classifier.dense" ) return name def __a ( A__ : Optional[int] , A__ : Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(A__ ) if "qkv" in key: SCREAMING_SNAKE_CASE = key.split("." ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = config.hidden_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[dim : dim * 2] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __a ( A__ : int ): SCREAMING_SNAKE_CASE = [ "module.v.head.weight", "module.v.head.bias", "module.v.head_dist.weight", "module.v.head_dist.bias", ] for k in ignore_keys: state_dict.pop(A__ , A__ ) @torch.no_grad() def __a ( A__ : Union[str, Any] , A__ : List[Any] , A__ : Optional[Any]=False ): SCREAMING_SNAKE_CASE = get_audio_spectrogram_transformer_config(A__ ) SCREAMING_SNAKE_CASE = { "ast-finetuned-audioset-10-10-0.4593": ( "https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.450": ( "https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.448": ( "https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.448-v2": ( "https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1" ), "ast-finetuned-audioset-12-12-0.447": ( "https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1" ), "ast-finetuned-audioset-14-14-0.443": ( "https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1" ), "ast-finetuned-audioset-16-16-0.442": ( "https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1" ), "ast-finetuned-speech-commands-v2": ( "https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1" ), } # load original state_dict SCREAMING_SNAKE_CASE = model_name_to_url[model_name] SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(A__ , map_location="cpu" ) # remove some keys remove_keys(A__ ) # rename some keys SCREAMING_SNAKE_CASE = convert_state_dict(A__ , A__ ) # load 🤗 model SCREAMING_SNAKE_CASE = ASTForAudioClassification(A__ ) model.eval() model.load_state_dict(A__ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 SCREAMING_SNAKE_CASE = -4.2_6_7_7_3_9_3 if "speech-commands" not in model_name else -6.8_4_5_9_7_8 SCREAMING_SNAKE_CASE = 4.5_6_8_9_9_7_4 if "speech-commands" not in model_name else 5.5_6_5_4_5_2_6 SCREAMING_SNAKE_CASE = 1024 if "speech-commands" not in model_name else 128 SCREAMING_SNAKE_CASE = ASTFeatureExtractor(mean=A__ , std=A__ , max_length=A__ ) if "speech-commands" in model_name: SCREAMING_SNAKE_CASE = load_dataset("speech_commands" , "v0.02" , split="validation" ) SCREAMING_SNAKE_CASE = dataset[0]["audio"]["array"] else: SCREAMING_SNAKE_CASE = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torchaudio.load(A__ ) SCREAMING_SNAKE_CASE = waveform.squeeze().numpy() SCREAMING_SNAKE_CASE = feature_extractor(A__ , sampling_rate=16000 , return_tensors="pt" ) # forward pass SCREAMING_SNAKE_CASE = model(**A__ ) SCREAMING_SNAKE_CASE = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": SCREAMING_SNAKE_CASE = torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": SCREAMING_SNAKE_CASE = torch.tensor([-1.1_9_8_6, -7.0_9_0_3, -8.2_7_1_8] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": SCREAMING_SNAKE_CASE = torch.tensor([-2.6_1_2_8, -8.0_0_8_0, -9.4_3_4_4] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": SCREAMING_SNAKE_CASE = torch.tensor([-1.5_0_8_0, -7.4_5_3_4, -8.8_9_1_7] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": SCREAMING_SNAKE_CASE = torch.tensor([-0.5_0_5_0, -6.5_8_3_3, -8.0_8_4_3] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": SCREAMING_SNAKE_CASE = torch.tensor([-0.3_8_2_6, -7.0_3_3_6, -8.2_4_1_3] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": SCREAMING_SNAKE_CASE = torch.tensor([-1.2_1_1_3, -6.9_1_0_1, -8.3_4_7_0] ) elif model_name == "ast-finetuned-speech-commands-v2": SCREAMING_SNAKE_CASE = torch.tensor([6.1_5_8_9, -8.0_5_6_6, -8.7_9_8_4] ) else: raise ValueError("Unknown model name" ) if not torch.allclose(logits[0, :3] , A__ , atol=1E-4 ): raise ValueError("Logits don't match" ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(A__ ).mkdir(exist_ok=A__ ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(A__ ) print(F"Saving feature extractor to {pytorch_dump_folder_path}" ) feature_extractor.save_pretrained(A__ ) if push_to_hub: print("Pushing model and feature extractor to the hub..." ) model.push_to_hub(F"MIT/{model_name}" ) feature_extractor.push_to_hub(F"MIT/{model_name}" ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='ast-finetuned-audioset-10-10-0.4593', type=str, help='Name of the Audio Spectrogram Transformer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __A : Tuple = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
707
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @slow @require_torch def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("bert-base-uncased" ) SCREAMING_SNAKE_CASE = bertabert.config.encoder.vocab_size SCREAMING_SNAKE_CASE = tokenizer.sep_token_id SCREAMING_SNAKE_CASE = tokenizer.cls_token_id SCREAMING_SNAKE_CASE = 128 SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) SCREAMING_SNAKE_CASE = train_dataset.select(range(32 ) ) SCREAMING_SNAKE_CASE = val_dataset.select(range(16 ) ) SCREAMING_SNAKE_CASE = 4 def _map_to_encoder_decoder_inputs(__lowerCamelCase : str ): # Tokenizer will automatically set [BOS] <text> [EOS] SCREAMING_SNAKE_CASE = tokenizer(batch["article"] , padding="max_length" , truncation=__lowerCamelCase , max_length=512 ) SCREAMING_SNAKE_CASE = tokenizer(batch["highlights"] , padding="max_length" , truncation=__lowerCamelCase , max_length=128 ) SCREAMING_SNAKE_CASE = inputs.input_ids SCREAMING_SNAKE_CASE = inputs.attention_mask SCREAMING_SNAKE_CASE = outputs.input_ids SCREAMING_SNAKE_CASE = outputs.input_ids.copy() SCREAMING_SNAKE_CASE = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] SCREAMING_SNAKE_CASE = outputs.attention_mask assert all(len(__lowerCamelCase ) == 512 for x in inputs.input_ids ) assert all(len(__lowerCamelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(__lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = pred.label_ids SCREAMING_SNAKE_CASE = pred.predictions # all unnecessary tokens are removed SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = sum([int(pred_str[i] == label_str[i] ) for i in range(len(__lowerCamelCase ) )] ) / len(__lowerCamelCase ) return {"accuracy": accuracy} # map train dataset SCREAMING_SNAKE_CASE = train_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset SCREAMING_SNAKE_CASE = val_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE = SeqaSeqTrainingArguments( output_dir=__lowerCamelCase , per_device_train_batch_size=__lowerCamelCase , per_device_eval_batch_size=__lowerCamelCase , predict_with_generate=__lowerCamelCase , evaluation_strategy="steps" , do_train=__lowerCamelCase , do_eval=__lowerCamelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer SCREAMING_SNAKE_CASE = SeqaSeqTrainer( model=__lowerCamelCase , args=__lowerCamelCase , compute_metrics=_compute_metrics , train_dataset=__lowerCamelCase , eval_dataset=__lowerCamelCase , tokenizer=__lowerCamelCase , ) # start training trainer.train()
698
0
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __A : Union[str, Any] = logging.get_logger(__name__) __A : int = 'https://openaipublic.azureedge.net/jukebox/models/' __A : Optional[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def __a ( A__ : int ): if key.endswith(".model.1.bias" ) and len(key.split("." ) ) > 10: SCREAMING_SNAKE_CASE = key.replace(".model.1.bias" , ".conv1d_1.bias" ) elif key.endswith(".model.1.weight" ) and len(key.split("." ) ) > 10: SCREAMING_SNAKE_CASE = key.replace(".model.1.weight" , ".conv1d_1.weight" ) elif key.endswith(".model.3.bias" ) and len(key.split("." ) ) > 10: SCREAMING_SNAKE_CASE = key.replace(".model.3.bias" , ".conv1d_2.bias" ) elif key.endswith(".model.3.weight" ) and len(key.split("." ) ) > 10: SCREAMING_SNAKE_CASE = key.replace(".model.3.weight" , ".conv1d_2.weight" ) if "conditioner_blocks.0." in key: SCREAMING_SNAKE_CASE = key.replace("conditioner_blocks.0" , "conditioner_blocks" ) if "prime_prior" in key: SCREAMING_SNAKE_CASE = key.replace("prime_prior" , "encoder" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: SCREAMING_SNAKE_CASE = key.replace(".emb." , "." ) if key.endswith("k" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(".k" , ".codebook" ) if "y_emb." in key: return key.replace("y_emb." , "metadata_embedding." ) if "x_emb.emb." in key: SCREAMING_SNAKE_CASE = key.replace("0.x_emb.emb" , "embed_tokens" ) if "prime_state_ln" in key: return key.replace("prime_state_ln" , "encoder.final_layer_norm" ) if ".ln" in key: return key.replace(".ln" , ".layer_norm" ) if "_ln" in key: return key.replace("_ln" , "_layer_norm" ) if "prime_state_proj" in key: return key.replace("prime_state_proj" , "encoder.proj_in" ) if "prime_x_out" in key: return key.replace("prime_x_out" , "encoder.lm_head" ) if "prior.x_out" in key: return key.replace("x_out" , "fc_proj_out" ) if "x_emb" in key: return key.replace("x_emb" , "embed_tokens" ) return key def __a ( A__ : Optional[Any] , A__ : Dict , A__ : Tuple , A__ : Optional[Any] ): SCREAMING_SNAKE_CASE = {} import re SCREAMING_SNAKE_CASE = re.compile(R"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile( R"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile(R"encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile(R"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile( R"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile(R"decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile(R"conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile( R"conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE = re.compile(R"conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_encoder_block_conv_in.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = int(groups[2] ) * 2 + int(groups[3] ) SCREAMING_SNAKE_CASE = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}" SCREAMING_SNAKE_CASE = re_encoder_block_conv_in.sub(A__ , A__ ) elif re_encoder_block_resnet.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_encoder_block_resnet.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = int(groups[2] ) * 2 + int(groups[3] ) SCREAMING_SNAKE_CASE = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}." SCREAMING_SNAKE_CASE = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" SCREAMING_SNAKE_CASE = prefix + resnet_block SCREAMING_SNAKE_CASE = re_encoder_block_resnet.sub(A__ , A__ ) elif re_encoder_block_proj_out.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_encoder_block_proj_out.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = F"encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}" SCREAMING_SNAKE_CASE = re_encoder_block_proj_out.sub(A__ , A__ ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_decoder_block_conv_out.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = int(groups[2] ) * 2 + int(groups[3] ) - 2 SCREAMING_SNAKE_CASE = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}" SCREAMING_SNAKE_CASE = re_decoder_block_conv_out.sub(A__ , A__ ) elif re_decoder_block_resnet.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_decoder_block_resnet.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = int(groups[2] ) * 2 + int(groups[3] ) - 2 SCREAMING_SNAKE_CASE = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}." SCREAMING_SNAKE_CASE = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" SCREAMING_SNAKE_CASE = prefix + resnet_block SCREAMING_SNAKE_CASE = re_decoder_block_resnet.sub(A__ , A__ ) elif re_decoder_block_proj_in.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_decoder_block_proj_in.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = F"decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}" SCREAMING_SNAKE_CASE = re_decoder_block_proj_in.sub(A__ , A__ ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_prior_cond_conv_out.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = int(groups[1] ) * 2 + int(groups[2] ) - 2 SCREAMING_SNAKE_CASE = F"conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}" SCREAMING_SNAKE_CASE = re_prior_cond_conv_out.sub(A__ , A__ ) elif re_prior_cond_resnet.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_prior_cond_resnet.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = int(groups[1] ) * 2 + int(groups[2] ) - 2 SCREAMING_SNAKE_CASE = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE = F"conditioner_blocks.upsampler.upsample_block.{block_index}." SCREAMING_SNAKE_CASE = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" SCREAMING_SNAKE_CASE = prefix + resnet_block SCREAMING_SNAKE_CASE = re_prior_cond_resnet.sub(A__ , A__ ) elif re_prior_cond_proj_in.fullmatch(A__ ): SCREAMING_SNAKE_CASE = re_prior_cond_proj_in.match(A__ ) SCREAMING_SNAKE_CASE = regex_match.groups() SCREAMING_SNAKE_CASE = F"conditioner_blocks.upsampler.proj_in.{groups[-1]}" SCREAMING_SNAKE_CASE = re_prior_cond_proj_in.sub(A__ , A__ ) # keep original key else: SCREAMING_SNAKE_CASE = original_key SCREAMING_SNAKE_CASE = replace_key(A__ ) if F"{key_prefix}.{key}" not in model_state_dict or key is None: print(F"failed converting {original_key} to {key}, does not match" ) # handle missmatched shape elif value.shape != model_state_dict[F"{key_prefix}.{key}"].shape: SCREAMING_SNAKE_CASE = model_state_dict[F"{key_prefix}.{key}"] print(F"{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match" ) SCREAMING_SNAKE_CASE = original_key SCREAMING_SNAKE_CASE = original_key SCREAMING_SNAKE_CASE = value return new_dict @torch.no_grad() def __a ( A__ : Any=None , A__ : Optional[int]=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" ): SCREAMING_SNAKE_CASE = requests.get(F"{PREFIX}{file}" , allow_redirects=A__ ) os.makedirs(F"{pytorch_dump_folder_path}/" , exist_ok=A__ ) open(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" , "wb" ).write(r.content ) SCREAMING_SNAKE_CASE = MODEL_MAPPING[model_name.split("/" )[-1]] SCREAMING_SNAKE_CASE = JukeboxConfig.from_pretrained(A__ ) SCREAMING_SNAKE_CASE = JukeboxModel(A__ ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} for i, dict_name in enumerate(A__ ): SCREAMING_SNAKE_CASE = torch.load(F"{pytorch_dump_folder_path}/{dict_name.split('/' )[-1]}" )["model"] SCREAMING_SNAKE_CASE = {} for k in old_dic.keys(): if k.endswith(".b" ): SCREAMING_SNAKE_CASE = old_dic[k] elif k.endswith(".w" ): SCREAMING_SNAKE_CASE = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: SCREAMING_SNAKE_CASE = old_dic[k] else: SCREAMING_SNAKE_CASE = old_dic[k] SCREAMING_SNAKE_CASE = "vqvae" if i == 0 else F"priors.{3 - i}" SCREAMING_SNAKE_CASE = fix_jukebox_keys(A__ , model.state_dict() , A__ , A__ ) weight_dict.append(A__ ) SCREAMING_SNAKE_CASE = weight_dict.pop(0 ) model.vqvae.load_state_dict(A__ ) for i in range(len(A__ ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(A__ ).mkdir(exist_ok=A__ ) with open(F"{pytorch_dump_folder_path}/mapping.json" , "w" ) as txtfile: json.dump(A__ , A__ ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(A__ ) return weight_dict if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __A : Dict = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
708
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, 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 ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , "num_attention_heads" ) ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : Optional[int]=64 , __lowerCamelCase : Dict=3 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : int=2 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Tuple=[128, 256, 384] , __lowerCamelCase : int=[4, 6, 8] , __lowerCamelCase : Tuple=[2, 3, 4] , __lowerCamelCase : List[str]=[16, 16, 16] , __lowerCamelCase : int=0 , __lowerCamelCase : List[Any]=[2, 2, 2] , __lowerCamelCase : List[str]=[2, 2, 2] , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=True , __lowerCamelCase : int=2 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = kernel_size SCREAMING_SNAKE_CASE = stride SCREAMING_SNAKE_CASE = padding SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = [ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[str] ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = LevitModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) SCREAMING_SNAKE_CASE = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def _snake_case ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = LevitForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) lowerCamelCase__ = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = LevitModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : Any ): return @unittest.skip(reason="Levit does not use inputs_embeds" ) def _snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason="Levit does not support input and output embeddings" ) def _snake_case ( self : Tuple ): pass @unittest.skip(reason="Levit does not output attentions" ) def _snake_case ( self : Tuple ): pass def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : List[Any] ): def check_hidden_states_output(__lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = len(self.model_tester.depths ) + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) SCREAMING_SNAKE_CASE = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : int ): pass def _snake_case ( self : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : int=False ): SCREAMING_SNAKE_CASE = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def _snake_case ( self : List[Any] ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(__lowerCamelCase ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(__lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.gradient_checkpointing_enable() model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(__lowerCamelCase ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}" ): SCREAMING_SNAKE_CASE = problem_type["title"] SCREAMING_SNAKE_CASE = problem_type["num_labels"] SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) SCREAMING_SNAKE_CASE = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=__lowerCamelCase ) as warning_list: SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def _snake_case ( self : List[Any] ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = LevitModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Dict ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([1.0_448, -0.3_745, -1.8_317] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
698
0
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = (UnCLIPScheduler,) def _snake_case ( self : Union[str, Any] , **__lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = { "num_train_timesteps": 1000, "variance_type": "fixed_small_log", "clip_sample": True, "clip_sample_range": 1.0, "prediction_type": "epsilon", } config.update(**__lowerCamelCase ) return config def _snake_case ( self : Any ): for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=__lowerCamelCase ) def _snake_case ( self : List[str] ): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=__lowerCamelCase ) def _snake_case ( self : Optional[int] ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__lowerCamelCase ) def _snake_case ( self : str ): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=__lowerCamelCase ) def _snake_case ( self : List[Any] ): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=__lowerCamelCase ) def _snake_case ( self : Union[str, Any] ): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=__lowerCamelCase , prev_timestep=__lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(variance_type="fixed_small_log" ) SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.00_00e-10 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_549_625 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.9_994_987 ) ) < 1e-5 def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(variance_type="learned_range" ) SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = 0.5 assert scheduler._get_variance(1 , predicted_variance=__lowerCamelCase ) - -10.1_712_790 < 1e-5 assert scheduler._get_variance(487 , predicted_variance=__lowerCamelCase ) - -5.7_998_052 < 1e-5 assert scheduler._get_variance(999 , predicted_variance=__lowerCamelCase ) - -0.0_010_011 < 1e-5 def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler.timesteps SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) for i, t in enumerate(__lowerCamelCase ): # 1. predict noise residual SCREAMING_SNAKE_CASE = model(__lowerCamelCase , __lowerCamelCase ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , generator=__lowerCamelCase ).prev_sample SCREAMING_SNAKE_CASE = pred_prev_sample SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_sum.item() - 252.2_682_495 ) < 1e-2 assert abs(result_mean.item() - 0.3_284_743 ) < 1e-3 def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(25 ) SCREAMING_SNAKE_CASE = scheduler.timesteps SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) for i, t in enumerate(__lowerCamelCase ): # 1. predict noise residual SCREAMING_SNAKE_CASE = model(__lowerCamelCase , __lowerCamelCase ) if i + 1 == timesteps.shape[0]: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE = scheduler.step( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , prev_timestep=__lowerCamelCase , generator=__lowerCamelCase ).prev_sample SCREAMING_SNAKE_CASE = pred_prev_sample SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_sum.item() - 258.2_044_983 ) < 1e-2 assert abs(result_mean.item() - 0.3_362_038 ) < 1e-3 def _snake_case ( self : Dict ): pass def _snake_case ( self : int ): pass
709
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): return None class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : int ): return None class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = [ # (model_name, model_kwargs) ("bert-base-cased", {}), ("gpt2", {"use_cache": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : Optional[int] ): from transformers import BertModel SCREAMING_SNAKE_CASE = ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"] with NamedTemporaryFile(mode="w+t" ) as vocab_file: vocab_file.write("\n".join(__lowerCamelCase ) ) vocab_file.flush() SCREAMING_SNAKE_CASE = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: SCREAMING_SNAKE_CASE = BertModel(BertConfig(vocab_size=len(__lowerCamelCase ) ) ) model.save_pretrained(__lowerCamelCase ) self._test_export(__lowerCamelCase , "pt" , 12 , __lowerCamelCase ) @require_tf @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(Path(__lowerCamelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) @require_torch @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(__lowerCamelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) def _snake_case ( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Tuple=None , **__lowerCamelCase : List[str] ): try: # Compute path with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE = Path(__lowerCamelCase ).joinpath("model.onnx" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) return path except Exception as e: self.fail(__lowerCamelCase ) @require_torch @require_tokenizers @slow def _snake_case ( self : Dict ): from transformers import BertModel SCREAMING_SNAKE_CASE = BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "pt" ) @require_tf @require_tokenizers @slow def _snake_case ( self : int ): from transformers import TFBertModel SCREAMING_SNAKE_CASE = TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "tf" ) def _snake_case ( self : int , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = FeatureExtractionPipeline(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = infer_shapes(__lowerCamelCase , __lowerCamelCase ) # Assert all variables are present self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __lowerCamelCase ) self.assertSequenceEqual(variable_names[3:] , __lowerCamelCase ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: "batch", 1: "sequence"} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["output_0"] , {0: "batch", 1: "sequence"} ) self.assertDictEqual(shapes["output_1"] , {0: "batch"} ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask", "token_type_ids"] SCREAMING_SNAKE_CASE = {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__lowerCamelCase ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__lowerCamelCase ) , set(__lowerCamelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__lowerCamelCase , (tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncNonContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__lowerCamelCase ) , 1 ) self.assertEqual(len(__lowerCamelCase ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["input_ids"] ) self.assertEqual(ordered_input_names[0] , "input_ids" ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = generate_identified_filename(Path("/home/something/my_fake_model.onnx" ) , "-test" ) self.assertEqual("/home/something/my_fake_model-test.onnx" , generated.as_posix() )
698
0
from __future__ import annotations from random import random from typing import Generic, TypeVar __A : int = TypeVar('KT') __A : List[str] = TypeVar('VT') class _SCREAMING_SNAKE_CASE ( Generic[KT, VT] ): '''simple docstring''' def __init__( self : Any , __lowerCamelCase : KT | str = "root" , __lowerCamelCase : VT | None = None ): SCREAMING_SNAKE_CASE = key SCREAMING_SNAKE_CASE = value SCREAMING_SNAKE_CASE = [] def __repr__( self : Optional[Any] ): return f"Node({self.key}: {self.value})" @property def _snake_case ( self : Optional[Any] ): return len(self.forward ) class _SCREAMING_SNAKE_CASE ( Generic[KT, VT] ): '''simple docstring''' def __init__( self : Any , __lowerCamelCase : float = 0.5 , __lowerCamelCase : int = 16 ): SCREAMING_SNAKE_CASE = Node[KT, VT]() SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = p SCREAMING_SNAKE_CASE = max_level def __str__( self : int ): SCREAMING_SNAKE_CASE = list(self ) if len(__lowerCamelCase ) == 0: return f"SkipList(level={self.level})" SCREAMING_SNAKE_CASE = max((len(str(__lowerCamelCase ) ) for item in items) , default=4 ) SCREAMING_SNAKE_CASE = max(__lowerCamelCase , 4 ) + 4 SCREAMING_SNAKE_CASE = self.head SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = node.forward.copy() lines.append(f"[{node.key}]".ljust(__lowerCamelCase , "-" ) + "* " * len(__lowerCamelCase ) ) lines.append(" " * label_size + "| " * len(__lowerCamelCase ) ) while len(node.forward ) != 0: SCREAMING_SNAKE_CASE = node.forward[0] lines.append( f"[{node.key}]".ljust(__lowerCamelCase , "-" ) + " ".join(str(n.key ) if n.key == node.key else "|" for n in forwards ) ) lines.append(" " * label_size + "| " * len(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE = node.forward lines.append("None".ljust(__lowerCamelCase ) + "* " * len(__lowerCamelCase ) ) return f"SkipList(level={self.level})\n" + "\n".join(__lowerCamelCase ) def __iter__( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.head while len(node.forward ) != 0: yield node.forward[0].key SCREAMING_SNAKE_CASE = node.forward[0] def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = 1 while random() < self.p and level < self.max_level: level += 1 return level def _snake_case ( self : int , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: SCREAMING_SNAKE_CASE = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(__lowerCamelCase ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def _snake_case ( self : List[str] , __lowerCamelCase : KT ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._locate_node(__lowerCamelCase ) if node is not None: for i, update_node in enumerate(__lowerCamelCase ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: SCREAMING_SNAKE_CASE = node.forward[i] else: SCREAMING_SNAKE_CASE = update_node.forward[:i] def _snake_case ( self : Optional[int] , __lowerCamelCase : KT , __lowerCamelCase : VT ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._locate_node(__lowerCamelCase ) if node is not None: SCREAMING_SNAKE_CASE = value else: SCREAMING_SNAKE_CASE = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , __lowerCamelCase ): update_vector.append(self.head ) SCREAMING_SNAKE_CASE = level SCREAMING_SNAKE_CASE = Node(__lowerCamelCase , __lowerCamelCase ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(__lowerCamelCase ) else: SCREAMING_SNAKE_CASE = new_node def _snake_case ( self : int , __lowerCamelCase : VT ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._locate_node(__lowerCamelCase ) if node is not None: return node.value return None def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.insert("Key1" , 3 ) skip_list.insert("Key2" , 12 ) skip_list.insert("Key3" , 41 ) skip_list.insert("Key4" , -19 ) SCREAMING_SNAKE_CASE = skip_list.head SCREAMING_SNAKE_CASE = {} while node.level != 0: SCREAMING_SNAKE_CASE = node.forward[0] SCREAMING_SNAKE_CASE = node.value assert len(A__ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.insert("Key1" , 10 ) skip_list.insert("Key1" , 12 ) skip_list.insert("Key5" , 7 ) skip_list.insert("Key7" , 10 ) skip_list.insert("Key10" , 5 ) skip_list.insert("Key7" , 7 ) skip_list.insert("Key5" , 5 ) skip_list.insert("Key10" , 10 ) SCREAMING_SNAKE_CASE = skip_list.head SCREAMING_SNAKE_CASE = {} while node.level != 0: SCREAMING_SNAKE_CASE = node.forward[0] SCREAMING_SNAKE_CASE = node.value if len(A__ ) != 4: print() assert len(A__ ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def __a ( ): SCREAMING_SNAKE_CASE = SkipList() assert skip_list.find("Some key" ) is None def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.insert("Key2" , 20 ) assert skip_list.find("Key2" ) == 20 skip_list.insert("Some Key" , 10 ) skip_list.insert("Key2" , 8 ) skip_list.insert("V" , 13 ) assert skip_list.find("Y" ) is None assert skip_list.find("Key2" ) == 8 assert skip_list.find("Some Key" ) == 10 assert skip_list.find("V" ) == 13 def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.delete("Some key" ) assert len(skip_list.head.forward ) == 0 def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.insert("Key1" , 12 ) skip_list.insert("V" , 13 ) skip_list.insert("X" , 14 ) skip_list.insert("Key2" , 15 ) skip_list.delete("V" ) skip_list.delete("Key2" ) assert skip_list.find("V" ) is None assert skip_list.find("Key2" ) is None def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.insert("Key1" , 12 ) skip_list.insert("V" , 13 ) skip_list.insert("X" , 14 ) skip_list.insert("Key2" , 15 ) skip_list.delete("V" ) assert skip_list.find("V" ) is None assert skip_list.find("X" ) == 14 assert skip_list.find("Key1" ) == 12 assert skip_list.find("Key2" ) == 15 skip_list.delete("X" ) assert skip_list.find("V" ) is None assert skip_list.find("X" ) is None assert skip_list.find("Key1" ) == 12 assert skip_list.find("Key2" ) == 15 skip_list.delete("Key1" ) assert skip_list.find("V" ) is None assert skip_list.find("X" ) is None assert skip_list.find("Key1" ) is None assert skip_list.find("Key2" ) == 15 skip_list.delete("Key2" ) assert skip_list.find("V" ) is None assert skip_list.find("X" ) is None assert skip_list.find("Key1" ) is None assert skip_list.find("Key2" ) is None def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.insert("Key1" , 12 ) skip_list.insert("V" , 13 ) skip_list.insert("X" , 142 ) skip_list.insert("Key2" , 15 ) skip_list.delete("X" ) def traverse_keys(A__ : Dict ): yield node.key for forward_node in node.forward: yield from traverse_keys(A__ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def __a ( ): def is_sorted(A__ : Dict ): return all(next_item >= item for item, next_item in zip(A__ , lst[1:] ) ) SCREAMING_SNAKE_CASE = SkipList() for i in range(10 ): skip_list.insert(A__ , A__ ) assert is_sorted(list(A__ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(A__ ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(A__ ) ) def __a ( ): for _ in range(100 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def __a ( ): SCREAMING_SNAKE_CASE = SkipList() skip_list.insert(2 , "2" ) skip_list.insert(4 , "4" ) skip_list.insert(6 , "4" ) skip_list.insert(4 , "5" ) skip_list.insert(8 , "4" ) skip_list.insert(9 , "4" ) skip_list.delete(4 ) print(A__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
710
from manim import * class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("CPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("GPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Model" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): rect.set_stroke(__lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__lowerCamelCase , buff=0.0 ) self.add(__lowerCamelCase ) cpu_targs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Loaded Checkpoint" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , aligned_edge=__lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) SCREAMING_SNAKE_CASE = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = MarkupText( f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(__lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) SCREAMING_SNAKE_CASE = MarkupText( f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__lowerCamelCase ) , Write(__lowerCamelCase ) ) self.play(Write(__lowerCamelCase , run_time=1 ) , Create(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): SCREAMING_SNAKE_CASE = fill.copy().set_fill(__lowerCamelCase , opacity=0.7 ) target.move_to(__lowerCamelCase ) first_animations.append(GrowFromCenter(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__lowerCamelCase , run_time=1.5 ) ) self.play(*__lowerCamelCase ) self.play(*__lowerCamelCase ) self.wait()
698
0
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = (DPMSolverSinglestepScheduler,) lowerCamelCase__ = (("num_inference_steps", 2_5),) def _snake_case ( self : str , **__lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = { "num_train_timesteps": 1000, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", "solver_order": 2, "prediction_type": "epsilon", "thresholding": False, "sample_max_value": 1.0, "algorithm_type": "dpmsolver++", "solver_type": "midpoint", "lambda_min_clipped": -float("inf" ), "variance_type": None, } config.update(**__lowerCamelCase ) return config def _snake_case ( self : List[Any] , __lowerCamelCase : Union[str, Any]=0 , **__lowerCamelCase : str ): SCREAMING_SNAKE_CASE = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE = kwargs.pop("num_inference_steps" , __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.dummy_sample SCREAMING_SNAKE_CASE = 0.1 * sample SCREAMING_SNAKE_CASE = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE = self.get_scheduler_config(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(__lowerCamelCase ) # copy over dummy past residuals SCREAMING_SNAKE_CASE = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler_class.from_pretrained(__lowerCamelCase ) new_scheduler.set_timesteps(__lowerCamelCase ) # copy over dummy past residuals SCREAMING_SNAKE_CASE = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = sample, sample for t in range(__lowerCamelCase , time_step + scheduler.config.solver_order + 1 ): SCREAMING_SNAKE_CASE = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ).prev_sample SCREAMING_SNAKE_CASE = new_scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _snake_case ( self : Any ): pass def _snake_case ( self : List[str] , __lowerCamelCase : str=0 , **__lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE = kwargs.pop("num_inference_steps" , __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.dummy_sample SCREAMING_SNAKE_CASE = 0.1 * sample SCREAMING_SNAKE_CASE = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(__lowerCamelCase ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler_class.from_pretrained(__lowerCamelCase ) # copy over dummy past residuals new_scheduler.set_timesteps(__lowerCamelCase ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ).prev_sample SCREAMING_SNAKE_CASE = new_scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _snake_case ( self : Dict , __lowerCamelCase : str=None , **__lowerCamelCase : Union[str, Any] ): if scheduler is None: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter scheduler.set_timesteps(__lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE = model(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ).prev_sample return sample def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter scheduler.set_timesteps(__lowerCamelCase ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): SCREAMING_SNAKE_CASE = model(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ).prev_sample SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_mean.item() - 0.2_574 ) < 1e-3 def _snake_case ( self : List[str] ): for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=__lowerCamelCase ) def _snake_case ( self : Any ): # make sure that iterating over schedulers with same config names gives same results # for defaults SCREAMING_SNAKE_CASE = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE = self.full_loop(scheduler=__lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_mean.item() - 0.2_791 ) < 1e-3 SCREAMING_SNAKE_CASE = DEISMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = UniPCMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = DPMSolverSinglestepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = self.full_loop(scheduler=__lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_mean.item() - 0.2_791 ) < 1e-3 def _snake_case ( self : Optional[Any] ): self.check_over_configs(thresholding=__lowerCamelCase ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__lowerCamelCase , prediction_type=__lowerCamelCase , sample_max_value=__lowerCamelCase , algorithm_type="dpmsolver++" , solver_order=__lowerCamelCase , solver_type=__lowerCamelCase , ) def _snake_case ( self : Tuple ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__lowerCamelCase ) def _snake_case ( self : Dict ): for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__lowerCamelCase , solver_type=__lowerCamelCase , prediction_type=__lowerCamelCase , algorithm_type=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = self.full_loop( solver_order=__lowerCamelCase , solver_type=__lowerCamelCase , prediction_type=__lowerCamelCase , algorithm_type=__lowerCamelCase , ) assert not torch.isnan(__lowerCamelCase ).any(), "Samples have nan numbers" def _snake_case ( self : Optional[int] ): self.check_over_configs(lower_order_final=__lowerCamelCase ) self.check_over_configs(lower_order_final=__lowerCamelCase ) def _snake_case ( self : Union[str, Any] ): self.check_over_configs(lambda_min_clipped=-float("inf" ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def _snake_case ( self : Union[str, Any] ): self.check_over_configs(variance_type=__lowerCamelCase ) self.check_over_configs(variance_type="learned_range" ) def _snake_case ( self : str ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=__lowerCamelCase , time_step=0 ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.full_loop() SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_mean.item() - 0.2_791 ) < 1e-3 def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = self.full_loop(use_karras_sigmas=__lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_mean.item() - 0.2_248 ) < 1e-3 def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = self.full_loop(prediction_type="v_prediction" ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_mean.item() - 0.1_453 ) < 1e-3 def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = self.full_loop(prediction_type="v_prediction" , use_karras_sigmas=__lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__lowerCamelCase ) ) assert abs(result_mean.item() - 0.0_649 ) < 1e-3 def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(thresholding=__lowerCamelCase , dynamic_thresholding_ratio=0 ) SCREAMING_SNAKE_CASE = scheduler_class(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter.half() scheduler.set_timesteps(__lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE = model(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ).prev_sample assert sample.dtype == torch.floataa
711
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 import ANY if is_vision_available(): from PIL import Image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Any , **__lowerCamelCase : Any ): pass @is_pipeline_test @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @require_torch def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowerCamelCase ) , [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @require_tf def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @slow @require_torch def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , )
698
0
import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def __a ( A__ : Any , A__ : Union[str, Any] , A__ : List[Any] , A__ : Optional[int]=1024 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] SCREAMING_SNAKE_CASE = list(zip(A__ , A__ ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = sorted_examples[0] def is_too_big(A__ : int ): return tok(A__ , return_tensors="pt" ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): SCREAMING_SNAKE_CASE = new_src + " " + src SCREAMING_SNAKE_CASE = new_tgt + " " + tgt if is_too_big(A__ ) or is_too_big(A__ ): # cant fit, finalize example finished_src.append(A__ ) finished_tgt.append(A__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = src, tgt else: # can fit, keep adding SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(A__ ) finished_tgt.append(A__ ) return finished_src, finished_tgt def __a ( A__ : Union[str, Any] , A__ : Path , A__ : Tuple , A__ : str ): SCREAMING_SNAKE_CASE = Path(A__ ) save_path.mkdir(exist_ok=A__ ) for split in ["train"]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = data_dir / F"{split}.source", data_dir / F"{split}.target" SCREAMING_SNAKE_CASE = [x.rstrip() for x in Path(A__ ).open().readlines()] SCREAMING_SNAKE_CASE = [x.rstrip() for x in Path(A__ ).open().readlines()] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = pack_examples(A__ , A__ , A__ , A__ ) print(F"packed {split} split from {len(A__ )} examples -> {len(A__ )}." ) Path(save_path / F"{split}.source" ).open("w" ).write("\n".join(A__ ) ) Path(save_path / F"{split}.target" ).open("w" ).write("\n".join(A__ ) ) for split in ["val", "test"]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = data_dir / F"{split}.source", data_dir / F"{split}.target" shutil.copyfile(A__ , save_path / F"{split}.source" ) shutil.copyfile(A__ , save_path / F"{split}.target" ) def __a ( ): SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument("--tok_name" , type=A__ , help="like facebook/bart-large-cnn,t5-base, etc." ) parser.add_argument("--max_seq_len" , type=A__ , default=128 ) parser.add_argument("--data_dir" , type=A__ ) parser.add_argument("--save_path" , type=A__ ) SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(A__ , Path(args.data_dir ) , args.max_seq_len , args.save_path ) if __name__ == "__main__": packer_cli()
712
__A : dict[str, float] = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.6_0217_6634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def __a ( A__ : str , A__ : str , A__ : float ): if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: SCREAMING_SNAKE_CASE = ( F"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" F"Valid values are: {', '.join(A__ )}" ) raise ValueError(A__ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
698
0
'''simple docstring''' import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , __lowerCamelCase : str , __lowerCamelCase : str=13 , __lowerCamelCase : Optional[int]=7 , __lowerCamelCase : List[Any]=True , __lowerCamelCase : str=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Dict=True , __lowerCamelCase : str=99 , __lowerCamelCase : Optional[int]=32 , __lowerCamelCase : Optional[int]=5 , __lowerCamelCase : Any=4 , __lowerCamelCase : List[str]=37 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Tuple=512 , __lowerCamelCase : Union[str, Any]=16 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Any=4 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_attention_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_choices def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE = None if self.use_attention_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = True lowerCamelCase__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = FlaxRoFormerModelTester(self ) @slow def _snake_case ( self : List[Any] ): for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("junnyu/roformer_chinese_small" , from_pt=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(np.ones((1, 1) ) ) self.assertIsNotNone(__lowerCamelCase ) @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" ) SCREAMING_SNAKE_CASE = jnp.array([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase )[0] SCREAMING_SNAKE_CASE = 50000 SCREAMING_SNAKE_CASE = (1, 6, vocab_size) self.assertEqual(output.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1e-4 ) )
713
from collections import deque from .hash_table import HashTable class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : Optional[int] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Optional[Any] ): super().__init__(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : Dict , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.values[key] def _snake_case ( self : Union[str, Any] ): return ( sum(self.charge_factor - len(__lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__lowerCamelCase ) == 0 ): return key return super()._collision_resolution(__lowerCamelCase , __lowerCamelCase )
698
0
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Optional[Any] , __lowerCamelCase : List[Any] ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["bs"] , model_result["ss"] ): SCREAMING_SNAKE_CASE = model_result["result"][batch_size][sequence_length] self.assertIsNotNone(__lowerCamelCase ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = "sgugger/tiny-distilbert-classification" SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , only_pretrain_model=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , torchscript=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , fpaa=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) # set architectures equal to `None` SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase , configs=[config] ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == "cpu" , "Can't do half precision" ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=__lowerCamelCase , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase , configs=[config] ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = "sshleifer/tinier_bart" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase , configs=[config] ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase , configs=[config] ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = "sshleifer/tinier_bart" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase , configs=[config] ) SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , save_to_csv=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__lowerCamelCase , "inf_time.csv" ) , train_memory_csv_file=os.path.join(__lowerCamelCase , "train_mem.csv" ) , inference_memory_csv_file=os.path.join(__lowerCamelCase , "inf_mem.csv" ) , train_time_csv_file=os.path.join(__lowerCamelCase , "train_time.csv" ) , env_info_csv_file=os.path.join(__lowerCamelCase , "env.csv" ) , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(__lowerCamelCase , "inf_time.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(__lowerCamelCase , "train_time.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(__lowerCamelCase , "inf_mem.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(__lowerCamelCase , "train_mem.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(__lowerCamelCase , "env.csv" ) ).exists() ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" def _check_summary_is_not_empty(__lowerCamelCase : str ): self.assertTrue(hasattr(__lowerCamelCase , "sequential" ) ) self.assertTrue(hasattr(__lowerCamelCase , "cumulative" ) ) self.assertTrue(hasattr(__lowerCamelCase , "current" ) ) self.assertTrue(hasattr(__lowerCamelCase , "total" ) ) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__lowerCamelCase , "log.txt" ) , log_print=__lowerCamelCase , trace_memory_line_by_line=__lowerCamelCase , multi_process=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = PyTorchBenchmark(__lowerCamelCase ) SCREAMING_SNAKE_CASE = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(__lowerCamelCase , "log.txt" ) ).exists() )
714
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : int = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "gpt_neo" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : str , __lowerCamelCase : Dict=50257 , __lowerCamelCase : Tuple=2048 , __lowerCamelCase : Optional[Any]=2048 , __lowerCamelCase : int=24 , __lowerCamelCase : int=[[["global", "local"], 12]] , __lowerCamelCase : int=16 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]=256 , __lowerCamelCase : Tuple="gelu_new" , __lowerCamelCase : Optional[Any]=0.0 , __lowerCamelCase : str=0.0 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[Any]=1e-5 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Dict=True , __lowerCamelCase : Dict=50256 , __lowerCamelCase : Optional[int]=50256 , **__lowerCamelCase : Dict , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_layers SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = window_size SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_dropout SCREAMING_SNAKE_CASE = embed_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = classifier_dropout SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id SCREAMING_SNAKE_CASE = attention_types SCREAMING_SNAKE_CASE = self.expand_attention_types_params(__lowerCamelCase ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " f"`config.num_layers = {self.num_layers}`. " "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) @staticmethod def _snake_case ( __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __a ( A__ : str , A__ : List[Any] , A__ : List[str] , A__ : Union[str, Any] ): import torch SCREAMING_SNAKE_CASE = input.size() SCREAMING_SNAKE_CASE = len(A__ ) SCREAMING_SNAKE_CASE = shape[dimension] SCREAMING_SNAKE_CASE = torch.arange(0 , A__ , A__ ) SCREAMING_SNAKE_CASE = torch.div(sizedim - size , A__ , rounding_mode="floor" ) + 1 SCREAMING_SNAKE_CASE = torch.arange(A__ ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE = [slice(A__ )] * rank SCREAMING_SNAKE_CASE = indices SCREAMING_SNAKE_CASE = input[s] SCREAMING_SNAKE_CASE = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(A__ ) def __a ( A__ : Union[str, Any] , A__ : Optional[int] ): import torch SCREAMING_SNAKE_CASE = torch.arange(1 , A__ ) SCREAMING_SNAKE_CASE = torch.remainder(A__ , A__ ) SCREAMING_SNAKE_CASE = remainders == 0 SCREAMING_SNAKE_CASE = candidates[divisor_indices] SCREAMING_SNAKE_CASE = torch.max(A__ ) return largest_divisor, torch.div(A__ , A__ , rounding_mode="floor" ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__lowerCamelCase , direction="inputs" ) SCREAMING_SNAKE_CASE = {0: "batch", 1: "past_sequence + sequence"} else: SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return common_inputs @property def _snake_case ( self : Optional[int] ): return self._config.num_heads def _snake_case ( self : Union[str, Any] , __lowerCamelCase : PreTrainedTokenizer , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[TensorType] = None , ): SCREAMING_SNAKE_CASE = super(__lowerCamelCase , self ).generate_dummy_inputs( __lowerCamelCase , batch_size=__lowerCamelCase , seq_length=__lowerCamelCase , is_pair=__lowerCamelCase , framework=__lowerCamelCase ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = common_inputs["input_ids"].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE = seqlen + 2 SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE = [ (torch.zeros(__lowerCamelCase ), torch.zeros(__lowerCamelCase )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE = common_inputs["attention_mask"] if self.use_past: SCREAMING_SNAKE_CASE = ordered_inputs["attention_mask"].dtype SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__lowerCamelCase , __lowerCamelCase , dtype=__lowerCamelCase )] , dim=1 ) return ordered_inputs @property def _snake_case ( self : Optional[int] ): return 13
698
0
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def __a ( A__ : Tuple , A__ : Union[str, Any] , A__ : Union[str, Any] , A__ : str , A__ : Any ): # Load configuration defined in the metadata file with open(A__ ) as metadata_file: SCREAMING_SNAKE_CASE = json.load(A__ ) SCREAMING_SNAKE_CASE = LukeConfig(use_entity_aware_attention=A__ , **metadata["model_config"] ) # Load in the weights from the checkpoint_path SCREAMING_SNAKE_CASE = torch.load(A__ , map_location="cpu" )["module"] # Load the entity vocab file SCREAMING_SNAKE_CASE = load_original_entity_vocab(A__ ) # add an entry for [MASK2] SCREAMING_SNAKE_CASE = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 SCREAMING_SNAKE_CASE = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks SCREAMING_SNAKE_CASE = AddedToken("<ent>" , lstrip=A__ , rstrip=A__ ) SCREAMING_SNAKE_CASE = AddedToken("<ent2>" , lstrip=A__ , rstrip=A__ ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F"Saving tokenizer to {pytorch_dump_folder_path}" ) tokenizer.save_pretrained(A__ ) with open(os.path.join(A__ , "tokenizer_config.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE = json.load(A__ ) SCREAMING_SNAKE_CASE = "MLukeTokenizer" with open(os.path.join(A__ , "tokenizer_config.json" ) , "w" ) as f: json.dump(A__ , A__ ) with open(os.path.join(A__ , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(A__ , A__ ) SCREAMING_SNAKE_CASE = MLukeTokenizer.from_pretrained(A__ ) # Initialize the embeddings of the special tokens SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(["@"] )[0] SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(["#"] )[0] SCREAMING_SNAKE_CASE = state_dict["embeddings.word_embeddings.weight"] SCREAMING_SNAKE_CASE = word_emb[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE = word_emb[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: SCREAMING_SNAKE_CASE = state_dict[bias_name] SCREAMING_SNAKE_CASE = decoder_bias[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE = decoder_bias[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: SCREAMING_SNAKE_CASE = F"encoder.layer.{layer_index}.attention.self." SCREAMING_SNAKE_CASE = state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE = state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks SCREAMING_SNAKE_CASE = state_dict["entity_embeddings.entity_embeddings.weight"] SCREAMING_SNAKE_CASE = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) SCREAMING_SNAKE_CASE = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' SCREAMING_SNAKE_CASE = state_dict["entity_predictions.bias"] SCREAMING_SNAKE_CASE = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) SCREAMING_SNAKE_CASE = torch.cat([entity_prediction_bias, entity_mask_bias] ) SCREAMING_SNAKE_CASE = LukeForMaskedLM(config=A__ ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) SCREAMING_SNAKE_CASE = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): SCREAMING_SNAKE_CASE = state_dict[key] else: SCREAMING_SNAKE_CASE = state_dict[key] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model.load_state_dict(A__ , strict=A__ ) if set(A__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F"Unexpected unexpected_keys: {unexpected_keys}" ) if set(A__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F"Unexpected missing_keys: {missing_keys}" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs SCREAMING_SNAKE_CASE = MLukeTokenizer.from_pretrained(A__ , task="entity_classification" ) SCREAMING_SNAKE_CASE = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." SCREAMING_SNAKE_CASE = (0, 9) SCREAMING_SNAKE_CASE = tokenizer(A__ , entity_spans=[span] , return_tensors="pt" ) SCREAMING_SNAKE_CASE = model(**A__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE = torch.Size((1, 33, 768) ) SCREAMING_SNAKE_CASE = torch.tensor([[0.0_8_9_2, 0.0_5_9_6, -0.2_8_1_9], [0.0_1_3_4, 0.1_1_9_9, 0.0_5_7_3], [-0.0_1_6_9, 0.0_9_2_7, 0.0_6_4_4]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , A__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE = torch.Size((1, 1, 768) ) SCREAMING_SNAKE_CASE = torch.tensor([[-0.1_4_8_2, 0.0_6_0_9, 0.0_3_2_2]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is" F" {expected_shape}" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , A__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction SCREAMING_SNAKE_CASE = MLukeTokenizer.from_pretrained(A__ ) SCREAMING_SNAKE_CASE = "Tokyo is the capital of <mask>." SCREAMING_SNAKE_CASE = (24, 30) SCREAMING_SNAKE_CASE = tokenizer(A__ , entity_spans=[span] , return_tensors="pt" ) SCREAMING_SNAKE_CASE = model(**A__ ) SCREAMING_SNAKE_CASE = encoding["input_ids"][0].tolist() SCREAMING_SNAKE_CASE = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) SCREAMING_SNAKE_CASE = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(A__ ) SCREAMING_SNAKE_CASE = outputs.entity_logits[0][0].argmax().item() SCREAMING_SNAKE_CASE = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(A__ ) ) model.save_pretrained(A__ ) def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = ["[MASK]", "[PAD]", "[UNK]"] SCREAMING_SNAKE_CASE = [json.loads(A__ ) for line in open(A__ )] SCREAMING_SNAKE_CASE = {} for entry in data: SCREAMING_SNAKE_CASE = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: SCREAMING_SNAKE_CASE = entity_id break SCREAMING_SNAKE_CASE = F"{language}:{entity_name}" SCREAMING_SNAKE_CASE = entity_id return new_mapping if __name__ == "__main__": __A : Any = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) __A : List[str] = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __A : Any = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = GPTaTokenizer lowerCamelCase__ = GPTaTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = {"add_prefix_space": True} lowerCamelCase__ = False def _snake_case ( self : Optional[Any] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(__lowerCamelCase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__lowerCamelCase ) ) def _snake_case ( self : List[str] , **__lowerCamelCase : List[str] ): kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _snake_case ( self : Tuple , **__lowerCamelCase : List[Any] ): kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] SCREAMING_SNAKE_CASE = tokenizer.tokenize(__lowerCamelCase , add_prefix_space=__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) def _snake_case ( self : Tuple ): if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer(add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" # Testing tokenization SCREAMING_SNAKE_CASE = tokenizer.tokenize(__lowerCamelCase , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE = tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE = self.get_rust_tokenizer(add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.encode(__lowerCamelCase , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) # Testing the unknown token SCREAMING_SNAKE_CASE = tokens + [rust_tokenizer.unk_token] SCREAMING_SNAKE_CASE = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) def _snake_case ( self : int , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Tuple ): # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _snake_case ( self : Any , __lowerCamelCase : Union[str, Any]=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) # Simple input SCREAMING_SNAKE_CASE = "This is a simple input" SCREAMING_SNAKE_CASE = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(__lowerCamelCase , tokenizer_r.encode , __lowerCamelCase , max_length=__lowerCamelCase , padding="max_length" ) # Simple input self.assertRaises(__lowerCamelCase , tokenizer_r.encode_plus , __lowerCamelCase , max_length=__lowerCamelCase , padding="max_length" ) # Simple input self.assertRaises( __lowerCamelCase , tokenizer_r.batch_encode_plus , __lowerCamelCase , max_length=__lowerCamelCase , padding="max_length" , ) # Pair input self.assertRaises(__lowerCamelCase , tokenizer_r.encode , __lowerCamelCase , max_length=__lowerCamelCase , padding="max_length" ) # Pair input self.assertRaises(__lowerCamelCase , tokenizer_r.encode_plus , __lowerCamelCase , max_length=__lowerCamelCase , padding="max_length" ) # Pair input self.assertRaises( __lowerCamelCase , tokenizer_r.batch_encode_plus , __lowerCamelCase , max_length=__lowerCamelCase , padding="max_length" , ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token="<pad>" ) # Simple input SCREAMING_SNAKE_CASE = "This is a simple input" SCREAMING_SNAKE_CASE = ["This is a simple input looooooooong", "This is a simple input"] SCREAMING_SNAKE_CASE = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] SCREAMING_SNAKE_CASE = tokenizer.pad_token_id SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , padding="max_length" , max_length=30 , return_tensors="np" ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , padding=__lowerCamelCase , truncate=__lowerCamelCase , return_tensors="np" ) SCREAMING_SNAKE_CASE = tokenizer(*__lowerCamelCase , padding="max_length" , max_length=60 , return_tensors="np" ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , padding=__lowerCamelCase , truncate=__lowerCamelCase , return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = "$$$" SCREAMING_SNAKE_CASE = GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=__lowerCamelCase , add_bos_token=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "This is a simple input" SCREAMING_SNAKE_CASE = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE = tokenizer.bos_token_id SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase ) self.assertEqual(out_s.input_ids[0] , __lowerCamelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) SCREAMING_SNAKE_CASE = tokenizer.decode(out_s.input_ids ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __lowerCamelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _snake_case ( self : Optional[int] ): pass def _snake_case ( self : str ): # TODO: change to self.get_tokenizers() when the fast version is implemented SCREAMING_SNAKE_CASE = [self.get_tokenizer(do_lower_case=__lowerCamelCase , add_bos_token=__lowerCamelCase )] for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE = "Encode this." SCREAMING_SNAKE_CASE = "This one too please." SCREAMING_SNAKE_CASE = tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase ) encoded_sequence += tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.encode_plus( __lowerCamelCase , __lowerCamelCase , add_special_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = encoded_sequence_dict["input_ids"] SCREAMING_SNAKE_CASE = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(__lowerCamelCase ) ] SCREAMING_SNAKE_CASE = [x for x in filtered_sequence if x is not None] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) @require_tokenizers class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ): # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "A photo of a cat" SCREAMING_SNAKE_CASE = tokenizer.encode( __lowerCamelCase , ) self.assertEqual(__lowerCamelCase , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained("test_opt" ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("./test_opt" ) SCREAMING_SNAKE_CASE = tokenizer.encode( __lowerCamelCase , ) self.assertEqual(__lowerCamelCase , [2, 250, 1345, 9, 10, 4758] ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("facebook/opt-350m" , use_slow=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "A photo of a cat" SCREAMING_SNAKE_CASE = tokenizer.encode( __lowerCamelCase , ) # Same as above self.assertEqual(__lowerCamelCase , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip("This test is failing because of a bug in the fast tokenizer" ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "bos" SCREAMING_SNAKE_CASE = tokenizer.get_vocab()["bos"] SCREAMING_SNAKE_CASE = "A photo of a cat" SCREAMING_SNAKE_CASE = tokenizer.encode( __lowerCamelCase , ) # We changed the bos token self.assertEqual(__lowerCamelCase , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained("./tok" ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("./tok" ) self.assertTrue(tokenizer.is_fast ) SCREAMING_SNAKE_CASE = tokenizer.encode( __lowerCamelCase , ) self.assertEqual(__lowerCamelCase , [31957, 250, 1345, 9, 10, 4758] )
716
import cmath import math def __a ( A__ : float , A__ : float , A__ : float , A__ : float ): SCREAMING_SNAKE_CASE = math.radians(A__ ) SCREAMING_SNAKE_CASE = math.radians(A__ ) # Convert voltage and current to rectangular form SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
698
0
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 from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _snake_case ( self : int ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return model @property def _snake_case ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , cross_attention_dim=10 , ) return model @property def _snake_case ( self : List[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D") , up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D") , ) SCREAMING_SNAKE_CASE = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return vqvae, unet @slow def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) SCREAMING_SNAKE_CASE = DDPMScheduler() SCREAMING_SNAKE_CASE = AudioDiffusionPipeline(vqvae=__lowerCamelCase , unet=self.dummy_unet , mel=__lowerCamelCase , scheduler=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(42 ) SCREAMING_SNAKE_CASE = pipe(generator=__lowerCamelCase , steps=4 ) SCREAMING_SNAKE_CASE = output.audios[0] SCREAMING_SNAKE_CASE = output.images[0] SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(42 ) SCREAMING_SNAKE_CASE = pipe(generator=__lowerCamelCase , steps=4 , return_dict=__lowerCamelCase ) SCREAMING_SNAKE_CASE = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) SCREAMING_SNAKE_CASE = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] SCREAMING_SNAKE_CASE = np.frombuffer(image_from_tuple.tobytes() , dtype="uint8" )[:10] SCREAMING_SNAKE_CASE = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 SCREAMING_SNAKE_CASE = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) SCREAMING_SNAKE_CASE = DDIMScheduler() SCREAMING_SNAKE_CASE = self.dummy_vqvae_and_unet SCREAMING_SNAKE_CASE = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=__lowerCamelCase , scheduler=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) np.random.seed(0 ) SCREAMING_SNAKE_CASE = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(42 ) SCREAMING_SNAKE_CASE = pipe(raw_audio=__lowerCamelCase , generator=__lowerCamelCase , start_step=5 , steps=10 ) SCREAMING_SNAKE_CASE = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) SCREAMING_SNAKE_CASE = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] SCREAMING_SNAKE_CASE = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 SCREAMING_SNAKE_CASE = self.dummy_unet_condition SCREAMING_SNAKE_CASE = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=__lowerCamelCase , mel=__lowerCamelCase , scheduler=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) np.random.seed(0 ) SCREAMING_SNAKE_CASE = torch.rand((1, 1, 10) ) SCREAMING_SNAKE_CASE = pipe(generator=__lowerCamelCase , encoding=__lowerCamelCase ) SCREAMING_SNAKE_CASE = output.images[0] SCREAMING_SNAKE_CASE = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] SCREAMING_SNAKE_CASE = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = torch_device SCREAMING_SNAKE_CASE = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-ddim-256" ) SCREAMING_SNAKE_CASE = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(42 ) SCREAMING_SNAKE_CASE = pipe(generator=__lowerCamelCase ) SCREAMING_SNAKE_CASE = output.audios[0] SCREAMING_SNAKE_CASE = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] SCREAMING_SNAKE_CASE = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] SCREAMING_SNAKE_CASE = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
717
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(A__ , A__ ) def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(A__ , A__ , bias=A__ ) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def __a ( A__ : Tuple , A__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = {} for old_key in state_dict.keys(): SCREAMING_SNAKE_CASE = old_key if "moe_layer.experts." in key: if expert_idx is not None: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts.0" , F"ffn.experts.expert_{expert_idx}" ) else: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: SCREAMING_SNAKE_CASE = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: SCREAMING_SNAKE_CASE = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("final_layer_norm" , "ff_layer_norm" ) SCREAMING_SNAKE_CASE = state_dict[old_key] return new_dict def __a ( A__ : List[str] , A__ : List[Any] , A__ : str , A__ : Union[str, Any] , A__ : str = WEIGHTS_NAME ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 os.makedirs(A__ , exist_ok=A__ ) for expert in range(A__ ): SCREAMING_SNAKE_CASE = switch_checkpoint_path + F"-rank-{expert}.pt" if os.path.isfile(A__ ): SCREAMING_SNAKE_CASE = torch.load(A__ )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = os.path.join( A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) torch.save(A__ , A__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A__ )[0]].dtype ) # Add the last block SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) SCREAMING_SNAKE_CASE = torch.load(switch_checkpoint_path + "-shared.pt" )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A__ ) == 1: SCREAMING_SNAKE_CASE = os.path.join(A__ , A__ ) torch.save(A__ , A__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A__ , A__ ) # Otherwise, let's build the index SCREAMING_SNAKE_CASE = {} for idx, shard in enumerate(A__ ): SCREAMING_SNAKE_CASE = weights_name.replace(".bin" , F"-{idx+1:05d}-of-{len(A__ ):05d}.bin" ) SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(A__ , os.path.join(A__ , A__ ) ) for key in shard: SCREAMING_SNAKE_CASE = shard_file # Add the metadata SCREAMING_SNAKE_CASE = {"total_size": total_size} SCREAMING_SNAKE_CASE = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(A__ , A__ ) , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE = json.dumps(A__ , indent=2 , sort_keys=A__ ) + "\n" f.write(A__ ) return metadata, index if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) __A : Optional[int] = parser.parse_args() __A , __A : Union[str, Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_2_8, args.dtype, ) __A : Any = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8 ) config.save_pretrained(args.pytorch_dump_folder_path) __A : Any = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
698
0
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, 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_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : int=13 , __lowerCamelCase : Union[str, Any]=7 , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Dict=True , __lowerCamelCase : int=True , __lowerCamelCase : str=True , __lowerCamelCase : Optional[Any]=99 , __lowerCamelCase : List[Any]=32 , __lowerCamelCase : int=2 , __lowerCamelCase : Dict=4 , __lowerCamelCase : Optional[Any]=37 , __lowerCamelCase : str="gelu" , __lowerCamelCase : Any=0.1 , __lowerCamelCase : Optional[Any]=0.1 , __lowerCamelCase : int=512 , __lowerCamelCase : Any=16 , __lowerCamelCase : Tuple=2 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Any=3 , __lowerCamelCase : List[Any]=4 , __lowerCamelCase : List[Any]=None , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = 13 SCREAMING_SNAKE_CASE = 7 SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = 99 SCREAMING_SNAKE_CASE = 384 SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = 37 SCREAMING_SNAKE_CASE = "gelu" SCREAMING_SNAKE_CASE = 0.1 SCREAMING_SNAKE_CASE = 0.1 SCREAMING_SNAKE_CASE = 512 SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 0.02 SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = 128 SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 9 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = None def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=__lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = TFConvBertModel(config=__lowerCamelCase ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE = [input_ids, input_mask] SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = TFConvBertForMaskedLM(config=__lowerCamelCase ) SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self : str , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFConvBertForSequenceClassification(config=__lowerCamelCase ) SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = TFConvBertForMultipleChoice(config=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFConvBertForTokenClassification(config=__lowerCamelCase ) SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = TFConvBertForQuestionAnswering(config=__lowerCamelCase ) SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) lowerCamelCase__ = ( { "feature-extraction": TFConvBertModel, "fill-mask": TFConvBertForMaskedLM, "question-answering": TFConvBertForQuestionAnswering, "text-classification": TFConvBertForSequenceClassification, "token-classification": TFConvBertForTokenClassification, "zero-shot": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = TFConvBertModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) @slow def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True if hasattr(__lowerCamelCase , "use_cache" ): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) SCREAMING_SNAKE_CASE = getattr(self.model_tester , "key_length" , __lowerCamelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = len(model(__lowerCamelCase ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase , saved_model=__lowerCamelCase ) SCREAMING_SNAKE_CASE = os.path.join(__lowerCamelCase , "saved_model" , "1" ) SCREAMING_SNAKE_CASE = tf.keras.models.load_model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) if self.is_encoder_decoder: SCREAMING_SNAKE_CASE = outputs["encoder_hidden_states"] SCREAMING_SNAKE_CASE = outputs["encoder_attentions"] else: SCREAMING_SNAKE_CASE = outputs["hidden_states"] SCREAMING_SNAKE_CASE = outputs["attentions"] self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(__lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) SCREAMING_SNAKE_CASE = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) SCREAMING_SNAKE_CASE = getattr(self.model_tester , "key_length" , __lowerCamelCase ) SCREAMING_SNAKE_CASE = getattr(self.model_tester , "key_length" , __lowerCamelCase ) def check_decoder_attentions_output(__lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) self.assertEqual(out_len % 2 , 0 ) SCREAMING_SNAKE_CASE = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) SCREAMING_SNAKE_CASE = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase )[0] SCREAMING_SNAKE_CASE = [1, 6, 768] self.assertEqual(output.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1e-4 )
718
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = BlipImageProcessor() SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" ) SCREAMING_SNAKE_CASE = BlipProcessor(__lowerCamelCase , __lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self : Dict , **__lowerCamelCase : Any ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).tokenizer def _snake_case ( self : List[Any] , **__lowerCamelCase : Optional[Any] ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).image_processor def _snake_case ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__lowerCamelCase , padding_value=1.0 ) SCREAMING_SNAKE_CASE = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCamelCase ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = image_processor(__lowerCamelCase , return_tensors="np" ) SCREAMING_SNAKE_CASE = processor(images=__lowerCamelCase , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
698
0
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(A__ , A__ ) def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(A__ , A__ , bias=A__ ) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def __a ( A__ : Tuple , A__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = {} for old_key in state_dict.keys(): SCREAMING_SNAKE_CASE = old_key if "moe_layer.experts." in key: if expert_idx is not None: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts.0" , F"ffn.experts.expert_{expert_idx}" ) else: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: SCREAMING_SNAKE_CASE = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: SCREAMING_SNAKE_CASE = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("final_layer_norm" , "ff_layer_norm" ) SCREAMING_SNAKE_CASE = state_dict[old_key] return new_dict def __a ( A__ : List[str] , A__ : List[Any] , A__ : str , A__ : Union[str, Any] , A__ : str = WEIGHTS_NAME ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 os.makedirs(A__ , exist_ok=A__ ) for expert in range(A__ ): SCREAMING_SNAKE_CASE = switch_checkpoint_path + F"-rank-{expert}.pt" if os.path.isfile(A__ ): SCREAMING_SNAKE_CASE = torch.load(A__ )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = os.path.join( A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) torch.save(A__ , A__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A__ )[0]].dtype ) # Add the last block SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) SCREAMING_SNAKE_CASE = torch.load(switch_checkpoint_path + "-shared.pt" )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A__ ) == 1: SCREAMING_SNAKE_CASE = os.path.join(A__ , A__ ) torch.save(A__ , A__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A__ , A__ ) # Otherwise, let's build the index SCREAMING_SNAKE_CASE = {} for idx, shard in enumerate(A__ ): SCREAMING_SNAKE_CASE = weights_name.replace(".bin" , F"-{idx+1:05d}-of-{len(A__ ):05d}.bin" ) SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(A__ , os.path.join(A__ , A__ ) ) for key in shard: SCREAMING_SNAKE_CASE = shard_file # Add the metadata SCREAMING_SNAKE_CASE = {"total_size": total_size} SCREAMING_SNAKE_CASE = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(A__ , A__ ) , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE = json.dumps(A__ , indent=2 , sort_keys=A__ ) + "\n" f.write(A__ ) return metadata, index if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) __A : Optional[int] = parser.parse_args() __A : Union[str, Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_2_8, args.dtype, ) __A : Any = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8 ) config.save_pretrained(args.pytorch_dump_folder_path) __A : Any = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
719
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, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Union[str, Any] ): pass def __a ( A__ : str ): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A : Tuple = ( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def _snake_case ( self : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model=__lowerCamelCase , tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) SCREAMING_SNAKE_CASE = "What is the placebo?" SCREAMING_SNAKE_CASE = [ { "image": load_image(__lowerCamelCase ), "question": question, }, { "image": image, "question": question, }, { "image": image, "question": question, "word_boxes": word_boxes, }, ] return dqa_pipeline, examples def _snake_case ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : int ): SCREAMING_SNAKE_CASE = dqa_pipeline(__lowerCamelCase , top_k=2 ) self.assertEqual( __lowerCamelCase , [ [ {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, {"score": ANY(__lowerCamelCase ), "answer": ANY(__lowerCamelCase ), "start": ANY(__lowerCamelCase ), "end": ANY(__lowerCamelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = pipeline("document-question-answering" , model="hf-internal-testing/tiny-random-layoutlmv2" ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "How many cats are there?" SCREAMING_SNAKE_CASE = [ {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) # We can optionnally pass directly the words and bounding boxes SCREAMING_SNAKE_CASE = "./tests/fixtures/tests_samples/COCO/000000039769.png" SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , words=__lowerCamelCase , boxes=__lowerCamelCase , top_k=2 ) self.assertEqual(__lowerCamelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=__lowerCamelCase , revision="3dc6de3" , max_seq_len=50 , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) SCREAMING_SNAKE_CASE = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 , ) SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , "" ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16}, ] , ) @slow @require_torch def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = pipeline( "document-question-answering" , model="naver-clova-ix/donut-base-finetuned-docvqa" , tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa" ) , feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa" , ) SCREAMING_SNAKE_CASE = INVOICE_URL SCREAMING_SNAKE_CASE = "What is the invoice number?" SCREAMING_SNAKE_CASE = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 ) self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , [{"answer": "us-001"}] ) @require_tf @unittest.skip("Document question answering not implemented in TF" ) def _snake_case ( self : List[Any] ): pass
698
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'microsoft/markuplm-base': 'https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json', 'microsoft/markuplm-large': 'https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "markuplm" def __init__( self : str , __lowerCamelCase : Any=30522 , __lowerCamelCase : str=768 , __lowerCamelCase : List[Any]=12 , __lowerCamelCase : Dict=12 , __lowerCamelCase : List[str]=3072 , __lowerCamelCase : Dict="gelu" , __lowerCamelCase : str=0.1 , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Tuple=512 , __lowerCamelCase : str=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : List[Any]=1e-12 , __lowerCamelCase : int=0 , __lowerCamelCase : Any=0 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Dict=256 , __lowerCamelCase : List[Any]=1024 , __lowerCamelCase : Optional[Any]=216 , __lowerCamelCase : str=1001 , __lowerCamelCase : Any=32 , __lowerCamelCase : List[str]=50 , __lowerCamelCase : Tuple="absolute" , __lowerCamelCase : Dict=True , __lowerCamelCase : Optional[int]=None , **__lowerCamelCase : Dict , ): super().__init__( pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = classifier_dropout # additional properties SCREAMING_SNAKE_CASE = max_depth SCREAMING_SNAKE_CASE = max_xpath_tag_unit_embeddings SCREAMING_SNAKE_CASE = max_xpath_subs_unit_embeddings SCREAMING_SNAKE_CASE = tag_pad_id SCREAMING_SNAKE_CASE = subs_pad_id SCREAMING_SNAKE_CASE = xpath_unit_hidden_size
720
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "facebook/bart-large-mnli" lowerCamelCase__ = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) lowerCamelCase__ = "text_classifier" lowerCamelCase__ = AutoTokenizer lowerCamelCase__ = AutoModelForSequenceClassification lowerCamelCase__ = ["text", ["text"]] lowerCamelCase__ = ["text"] def _snake_case ( self : Optional[Any] ): super().setup() SCREAMING_SNAKE_CASE = self.model.config SCREAMING_SNAKE_CASE = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): SCREAMING_SNAKE_CASE = int(__lowerCamelCase ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def _snake_case ( self : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = labels return self.pre_processor( [text] * len(__lowerCamelCase ) , [f"This example is {label}" for label in labels] , return_tensors="pt" , padding="max_length" , ) def _snake_case ( self : str , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = outputs.logits SCREAMING_SNAKE_CASE = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
698
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 Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed __A : Union[str, Any] = 'true' def __a ( A__ : List[str] , A__ : Dict=82 , A__ : int=16 ): '''simple docstring''' set_seed(42 ) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(A__ ) SCREAMING_SNAKE_CASE = RegressionDataset(length=A__ ) SCREAMING_SNAKE_CASE = DataLoader(A__ , batch_size=A__ ) model.to(accelerator.device ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(A__ , A__ ) return model, ddp_model, dataloader def __a ( A__ : Accelerator , A__ : Union[str, Any]=False ): '''simple docstring''' SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased" ) SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" , split="validation" ) def tokenize_function(A__ : List[Any] ): SCREAMING_SNAKE_CASE = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=A__ , max_length=A__ ) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( A__ , batched=A__ , remove_columns=["idx", "sentence1", "sentence2"] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(A__ : int ): if use_longest: return tokenizer.pad(A__ , padding="longest" , return_tensors="pt" ) return tokenizer.pad(A__ , padding="max_length" , max_length=128 , return_tensors="pt" ) return DataLoader(A__ , shuffle=A__ , collate_fn=A__ , batch_size=16 ) def __a ( A__ : Any , A__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=A__ , split_batches=A__ ) SCREAMING_SNAKE_CASE = get_dataloader(A__ , not dispatch_batches ) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( "hf-internal-testing/mrpc-bert-base-cased" , return_dict=A__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(A__ , A__ ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def __a ( A__ : Optional[Any] , A__ : Union[str, Any] , A__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(A__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(A__ ) targs.append(A__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(A__ ), torch.cat(A__ ) return logits, targs def __a ( A__ : Accelerator , A__ : List[Any]=82 , A__ : Tuple=False , A__ : Union[str, Any]=False , A__ : Any=16 ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(A__ , A__ , A__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(A__ , A__ , A__ ) assert ( len(A__ ) == num_samples ), F"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(A__ )}" def __a ( A__ : bool = False , A__ : bool = False ): '''simple docstring''' SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(A__ , A__ ) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup["no"] model.to(A__ ) model.eval() for batch in dataloader: batch.to(A__ ) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**A__ ) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=A__ , references=batch["labels"] ) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup["ddp"] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**A__ ) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE = batch["labels"] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=A__ , references=A__ ) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), F"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n" def __a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE = Accelerator(split_batches=A__ , dispatch_batches=A__ ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print("**Testing gather_for_metrics**" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`" ) test_mrpc(A__ , A__ ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("**Test torch metrics**" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=A__ , dispatch_batches=A__ ) if accelerator.is_local_main_process: print(F"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99" ) test_torch_metrics(A__ , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("**Test last batch is not dropped when perfectly divisible**" ) SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(A__ , 512 ) accelerator.state._reset_state() def __a ( A__ : List[str] ): '''simple docstring''' main() if __name__ == "__main__": main()
721
# 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 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __a ( A__ : str=None ): if subparsers is not None: SCREAMING_SNAKE_CASE = subparsers.add_parser("test" ) else: SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=A__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=A__ ) return parser def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: SCREAMING_SNAKE_CASE = script_name else: SCREAMING_SNAKE_CASE = F"--config_file={args.config_file} {script_name}" SCREAMING_SNAKE_CASE = ["accelerate-launch"] + test_args.split() SCREAMING_SNAKE_CASE = execute_subprocess_async(A__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __a ( ): SCREAMING_SNAKE_CASE = test_command_parser() SCREAMING_SNAKE_CASE = parser.parse_args() test_command(A__ ) if __name__ == "__main__": main()
698
0
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[Any] = logging.get_logger(__name__) __A : int = '▁' __A : Any = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} __A : List[str] = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } __A : Optional[int] = {'vinai/bartpho-syllable': 1_0_2_4} class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ["input_ids", "attention_mask"] def __init__( self : Dict , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any]="<s>" , __lowerCamelCase : str="</s>" , __lowerCamelCase : Tuple="</s>" , __lowerCamelCase : Optional[Any]="<s>" , __lowerCamelCase : Optional[int]="<unk>" , __lowerCamelCase : Dict="<pad>" , __lowerCamelCase : Dict="<mask>" , __lowerCamelCase : Optional[Dict[str, Any]] = None , **__lowerCamelCase : List[Any] , ): # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) SCREAMING_SNAKE_CASE = vocab_file SCREAMING_SNAKE_CASE = monolingual_vocab_file SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__lowerCamelCase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(__lowerCamelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE = cnt cnt += 1 with open(__lowerCamelCase , "r" , encoding="utf-8" ) as f: for line in f.readlines(): SCREAMING_SNAKE_CASE = line.strip().split()[0] SCREAMING_SNAKE_CASE = len(self.fairseq_tokens_to_ids ) if str(__lowerCamelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE = len(self.fairseq_tokens_to_ids ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Tuple ): SCREAMING_SNAKE_CASE = self.__dict__.copy() SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() return state def __setstate__( self : Dict , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self : List[str] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def _snake_case ( self : Any , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _snake_case ( self : int ): return len(self.fairseq_ids_to_tokens ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self : Tuple , __lowerCamelCase : str ): return self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) def _snake_case ( self : int , __lowerCamelCase : int ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _snake_case ( self : str , __lowerCamelCase : str ): return self.fairseq_ids_to_tokens[index] def _snake_case ( self : str , __lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = "".join(__lowerCamelCase ).replace(__lowerCamelCase , " " ).strip() return out_string def _snake_case ( self : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): if not os.path.isdir(__lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["monolingual_vocab_file"] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( __lowerCamelCase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(__lowerCamelCase , "w" , encoding="utf-8" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f"{str(__lowerCamelCase )} \n" ) return out_vocab_file, out_monolingual_vocab_file
700
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A : Optional[int] = logging.get_logger(__name__) __A : List[str] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } __A : Tuple = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } __A : Dict = {'facebook/blenderbot-3B': 1_2_8} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __a ( ): SCREAMING_SNAKE_CASE = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) SCREAMING_SNAKE_CASE = bs[:] SCREAMING_SNAKE_CASE = 0 for b in range(2**8 ): if b not in bs: bs.append(A__ ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE = [chr(A__ ) for n in cs] return dict(zip(A__ , A__ ) ) def __a ( A__ : Optional[int] ): SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE = char return pairs class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ["input_ids", "attention_mask"] def __init__( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any]="replace" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : List[Any]="</s>" , __lowerCamelCase : Dict="</s>" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : Optional[Any]="<unk>" , __lowerCamelCase : str="<pad>" , __lowerCamelCase : List[Any]="<mask>" , __lowerCamelCase : List[Any]=False , **__lowerCamelCase : Tuple , ): SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else bos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else eos_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else sep_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else cls_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else unk_token SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token super().__init__( errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , **__lowerCamelCase , ) with open(__lowerCamelCase , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE = json.load(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE = bytes_to_unicode() SCREAMING_SNAKE_CASE = {v: k for k, v in self.byte_encoder.items()} with open(__lowerCamelCase , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _snake_case ( self : Dict ): return len(self.encoder ) def _snake_case ( self : int ): return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self : Tuple , __lowerCamelCase : List[str] ): if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE = min(__lowerCamelCase , key=lambda __lowerCamelCase : self.bpe_ranks.get(__lowerCamelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = bigram SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while i < len(__lowerCamelCase ): try: SCREAMING_SNAKE_CASE = word.index(__lowerCamelCase , __lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE = j if word[i] == first and i < len(__lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE = new_word if len(__lowerCamelCase ) == 1: break else: SCREAMING_SNAKE_CASE = get_pairs(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = word return word def _snake_case ( self : str , __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for token in re.findall(self.pat , __lowerCamelCase ): SCREAMING_SNAKE_CASE = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCamelCase ).split(" " ) ) return bpe_tokens def _snake_case ( self : List[str] , __lowerCamelCase : str ): return self.encoder.get(__lowerCamelCase , self.encoder.get(self.unk_token ) ) def _snake_case ( self : Optional[int] , __lowerCamelCase : Tuple ): return self.decoder.get(__lowerCamelCase ) def _snake_case ( self : Tuple , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = "".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _snake_case ( self : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): if not os.path.isdir(__lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase ) + "\n" ) SCREAMING_SNAKE_CASE = 0 with open(__lowerCamelCase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE = token_index writer.write(" ".join(__lowerCamelCase ) + "\n" ) index += 1 return vocab_file, merge_file def _snake_case ( self : Tuple , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def _snake_case ( self : str , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : Any , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict=False , **__lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowerCamelCase ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE = " " + text return (text, kwargs) def _snake_case ( self : Dict , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): return token_ids_a + [self.eos_token_id] def _snake_case ( self : Tuple , __lowerCamelCase : "Conversation" ): SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(" " + text ) else: # Generated responses should contain them already. inputs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = " ".join(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.encode(__lowerCamelCase ) if len(__lowerCamelCase ) > self.model_max_length: SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens." ) return input_ids
698
0
import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __A : Dict = threading.Lock() __A : Optional[logging.Handler] = None __A : Any = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __A : int = logging.WARNING __A : int = True def __a ( ): SCREAMING_SNAKE_CASE = os.getenv("TRANSFORMERS_VERBOSITY" , A__ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, " F"has to be one of: { ', '.join(log_levels.keys() ) }" ) return _default_log_level def __a ( ): return __name__.split("." )[0] def __a ( ): return logging.getLogger(_get_library_name() ) def __a ( ): global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return SCREAMING_SNAKE_CASE = logging.StreamHandler() # Set sys.stderr as stream. SCREAMING_SNAKE_CASE = sys.stderr.flush # Apply our default configuration to the library root logger. SCREAMING_SNAKE_CASE = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) SCREAMING_SNAKE_CASE = False def __a ( ): global _default_handler with _lock: if not _default_handler: return SCREAMING_SNAKE_CASE = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) SCREAMING_SNAKE_CASE = None def __a ( ): return log_levels def __a ( A__ : Optional[str] = None ): if name is None: SCREAMING_SNAKE_CASE = _get_library_name() _configure_library_root_logger() return logging.getLogger(A__ ) def __a ( ): _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def __a ( A__ : int ): _configure_library_root_logger() _get_library_root_logger().setLevel(A__ ) def __a ( ): return set_verbosity(A__ ) def __a ( ): return set_verbosity(A__ ) def __a ( ): return set_verbosity(A__ ) def __a ( ): return set_verbosity(A__ ) def __a ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def __a ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def __a ( A__ : logging.Handler ): _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(A__ ) def __a ( A__ : logging.Handler ): _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(A__ ) def __a ( ): _configure_library_root_logger() SCREAMING_SNAKE_CASE = False def __a ( ): _configure_library_root_logger() SCREAMING_SNAKE_CASE = True def __a ( ): SCREAMING_SNAKE_CASE = _get_library_root_logger().handlers for handler in handlers: SCREAMING_SNAKE_CASE = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" ) handler.setFormatter(A__ ) def __a ( ): SCREAMING_SNAKE_CASE = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(A__ ) def __a ( self : List[Any] , *A__ : Union[str, Any] , **A__ : List[str] ): SCREAMING_SNAKE_CASE = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , A__ ) if no_advisory_warnings: return self.warning(*A__ , **A__ ) __A : int = warning_advice @functools.lru_cache(A__ ) def __a ( self : Dict , *A__ : Optional[int] , **A__ : Dict ): self.warning(*A__ , **A__ ) __A : Tuple = warning_once class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : Union[str, Any] ): # pylint: disable=unused-argument SCREAMING_SNAKE_CASE = args[0] if args else None def __iter__( self : List[Any] ): return iter(self._iterator ) def __getattr__( self : List[Any] , __lowerCamelCase : Tuple ): def empty_fn(*__lowerCamelCase : Tuple , **__lowerCamelCase : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : Any ): return self def __exit__( self : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ): return class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __call__( self : Optional[int] , *__lowerCamelCase : Dict , **__lowerCamelCase : List[Any] ): if _tqdm_active: return tqdm_lib.tqdm(*__lowerCamelCase , **__lowerCamelCase ) else: return EmptyTqdm(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : Tuple , *__lowerCamelCase : int , **__lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : List[Any] ): if _tqdm_active: return tqdm_lib.tqdm.get_lock() __A : List[str] = _tqdm_cls() def __a ( ): global _tqdm_active return bool(_tqdm_active ) def __a ( ): global _tqdm_active SCREAMING_SNAKE_CASE = True hf_hub_utils.enable_progress_bars() def __a ( ): global _tqdm_active SCREAMING_SNAKE_CASE = False hf_hub_utils.disable_progress_bars()
701
from __future__ import annotations from cmath import sqrt def __a ( A__ : int , A__ : int , A__ : int ): if a == 0: raise ValueError("Coefficient 'a' must not be zero." ) SCREAMING_SNAKE_CASE = b * b - 4 * a * c SCREAMING_SNAKE_CASE = (-b + sqrt(A__ )) / (2 * a) SCREAMING_SNAKE_CASE = (-b - sqrt(A__ )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def __a ( ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = quadratic_roots(a=5 , b=6 , c=1 ) print(F"The solutions are: {solutiona} and {solutiona}" ) if __name__ == "__main__": main()
698
0
import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput __A : str = 'scheduler_config.json' class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = 1 lowerCamelCase__ = 2 lowerCamelCase__ = 3 lowerCamelCase__ = 4 lowerCamelCase__ = 5 lowerCamelCase__ = 6 lowerCamelCase__ = 7 lowerCamelCase__ = 8 lowerCamelCase__ = 9 lowerCamelCase__ = 1_0 lowerCamelCase__ = 1_1 lowerCamelCase__ = 1_2 lowerCamelCase__ = 1_3 lowerCamelCase__ = 1_4 @dataclass class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = 4_2 class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowerCamelCase__ = SCHEDULER_CONFIG_NAME lowerCamelCase__ = [] lowerCamelCase__ = True @classmethod def _snake_case ( cls : str , __lowerCamelCase : Dict[str, Any] = None , __lowerCamelCase : Optional[str] = None , __lowerCamelCase : List[str]=False , **__lowerCamelCase : int , ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cls.load_config( pretrained_model_name_or_path=__lowerCamelCase , subfolder=__lowerCamelCase , return_unused_kwargs=__lowerCamelCase , return_commit_hash=__lowerCamelCase , **__lowerCamelCase , ) return cls.from_config(__lowerCamelCase , return_unused_kwargs=__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : Tuple , __lowerCamelCase : Union[str, os.PathLike] , __lowerCamelCase : bool = False , **__lowerCamelCase : Optional[Any] ): self.save_config(save_directory=__lowerCamelCase , push_to_hub=__lowerCamelCase , **__lowerCamelCase ) @property def _snake_case ( self : Optional[Any] ): return self._get_compatibles() @classmethod def _snake_case ( cls : Optional[int] ): SCREAMING_SNAKE_CASE = list(set([cls.__name__] + cls._compatibles ) ) SCREAMING_SNAKE_CASE = importlib.import_module(__name__.split("." )[0] ) SCREAMING_SNAKE_CASE = [ getattr(__lowerCamelCase , __lowerCamelCase ) for c in compatible_classes_str if hasattr(__lowerCamelCase , __lowerCamelCase ) ] return compatible_classes
702
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_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(greedy_ids[0] ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase ) SCREAMING_SNAKE_CASE = greedy_ids[:, input_ids.shape[1] :] SCREAMING_SNAKE_CASE = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_prompt=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=10 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE = cs.out[:-1] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("distilgpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = torch.ones((1, 5) , device=__lowerCamelCase ).long() * model.config.bos_token_id with CaptureStdout() as cs: SCREAMING_SNAKE_CASE = TextStreamer(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) model.generate(__lowerCamelCase , max_new_tokens=1 , do_sample=__lowerCamelCase , streamer=__lowerCamelCase ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token SCREAMING_SNAKE_CASE = cs.out[:-1] # Remove the final "\n" SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = TextIteratorStreamer(__lowerCamelCase , timeout=0.001 ) SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE = Thread(target=model.generate , kwargs=__lowerCamelCase ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE = "" for new_text in streamer: streamer_text += new_text
698
0
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, 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 ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , "num_attention_heads" ) ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : Optional[int]=64 , __lowerCamelCase : Dict=3 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : int=2 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Tuple=[128, 256, 384] , __lowerCamelCase : int=[4, 6, 8] , __lowerCamelCase : Tuple=[2, 3, 4] , __lowerCamelCase : List[str]=[16, 16, 16] , __lowerCamelCase : int=0 , __lowerCamelCase : List[Any]=[2, 2, 2] , __lowerCamelCase : List[str]=[2, 2, 2] , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=True , __lowerCamelCase : int=2 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = kernel_size SCREAMING_SNAKE_CASE = stride SCREAMING_SNAKE_CASE = padding SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = [ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[str] ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = LevitModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) SCREAMING_SNAKE_CASE = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def _snake_case ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = LevitForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) lowerCamelCase__ = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = LevitModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : Any ): return @unittest.skip(reason="Levit does not use inputs_embeds" ) def _snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason="Levit does not support input and output embeddings" ) def _snake_case ( self : Tuple ): pass @unittest.skip(reason="Levit does not output attentions" ) def _snake_case ( self : Tuple ): pass def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : List[Any] ): def check_hidden_states_output(__lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = len(self.model_tester.depths ) + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) SCREAMING_SNAKE_CASE = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : int ): pass def _snake_case ( self : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : int=False ): SCREAMING_SNAKE_CASE = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def _snake_case ( self : List[Any] ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(__lowerCamelCase ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(__lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.gradient_checkpointing_enable() model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(__lowerCamelCase ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}" ): SCREAMING_SNAKE_CASE = problem_type["title"] SCREAMING_SNAKE_CASE = problem_type["num_labels"] SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) SCREAMING_SNAKE_CASE = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=__lowerCamelCase ) as warning_list: SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def _snake_case ( self : List[Any] ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = LevitModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Dict ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([1.0_448, -0.3_745, -1.8_317] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
703
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Union[str, Any] = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __A : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __a ( A__ : List[Any] ): if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) __A : Union[str, Any] = parser.parse_args() __A : int = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
704
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __A : Optional[Any] = datasets.load_iris() __A : Optional[Any] = np.array(data['data']) __A : Optional[int] = np.array(data['target']) __A : Union[str, Any] = data['target_names'] __A , __A , __A , __A : Optional[int] = train_test_split(X, y) def __a ( A__ : Optional[int] , A__ : Dict ): return np.linalg.norm(np.array(A__ ) - np.array(A__ ) ) def __a ( A__ : Optional[Any] , A__ : int , A__ : Dict , A__ : Optional[Any] , A__ : Dict=5 ): SCREAMING_SNAKE_CASE = zip(A__ , A__ ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE = [] for data_point in data: SCREAMING_SNAKE_CASE = euclidean_distance(data_point[0] , A__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE = [i[1] for i in sorted(A__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE = Counter(A__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
698
0
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin __A : str = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = SpeechTaTokenizer lowerCamelCase__ = False lowerCamelCase__ = True def _snake_case ( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = SpeechTaTokenizer(__lowerCamelCase ) SCREAMING_SNAKE_CASE = AddedToken("<mask>" , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) SCREAMING_SNAKE_CASE = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self : str , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = "this is a test" SCREAMING_SNAKE_CASE = "this is a test" return input_text, output_text def _snake_case ( self : Dict , __lowerCamelCase : str , __lowerCamelCase : str=False , __lowerCamelCase : str=20 , __lowerCamelCase : str=5 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_input_output_texts(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.decode(__lowerCamelCase , clean_up_tokenization_spaces=__lowerCamelCase ) return text, ids def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = "<pad>" SCREAMING_SNAKE_CASE = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCamelCase ) , __lowerCamelCase ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-4] , "œ" ) self.assertEqual(vocab_keys[-2] , "<mask>" ) self.assertEqual(vocab_keys[-1] , "<ctc_blank>" ) self.assertEqual(len(__lowerCamelCase ) , 81 ) def _snake_case ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=__lowerCamelCase ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE = tokenizer.vocab_size SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) self.assertNotEqual(__lowerCamelCase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) SCREAMING_SNAKE_CASE = ["aaaaa bbbbbb", "cccccccccdddddddd"] SCREAMING_SNAKE_CASE = tokenizer.add_tokens(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.vocab_size SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) self.assertNotEqual(__lowerCamelCase , 0 ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , len(__lowerCamelCase ) ) self.assertEqual(__lowerCamelCase , all_size + len(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=__lowerCamelCase ) self.assertGreaterEqual(len(__lowerCamelCase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) SCREAMING_SNAKE_CASE = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} SCREAMING_SNAKE_CASE = tokenizer.add_special_tokens(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.vocab_size SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) self.assertNotEqual(__lowerCamelCase , 0 ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , len(__lowerCamelCase ) ) self.assertEqual(__lowerCamelCase , all_size_a + len(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=__lowerCamelCase ) self.assertGreaterEqual(len(__lowerCamelCase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def _snake_case ( self : str ): pass def _snake_case ( self : Any ): pass def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = tokenizer.tokenize("This is a test" ) # fmt: off self.assertListEqual(__lowerCamelCase , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) SCREAMING_SNAKE_CASE = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __lowerCamelCase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) # fmt: off self.assertListEqual(__lowerCamelCase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) @slow def _snake_case ( self : int ): # Use custom sequence because this tokenizer does not handle numbers. SCREAMING_SNAKE_CASE = [ "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " "conditioning on both left and right context in all layers.", "The quick brown fox jumps over the lazy dog.", ] # fmt: off SCREAMING_SNAKE_CASE = { "input_ids": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowerCamelCase , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=__lowerCamelCase , )
705
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 __A : Union[str, Any] = logging.get_logger(__name__) __A : Dict = { 'microsoft/resnet-50': 'https://huggingface.co/microsoft/resnet-50/blob/main/config.json', } class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ): '''simple docstring''' lowerCamelCase__ = "resnet" lowerCamelCase__ = ["basic", "bottleneck"] def __init__( self : Optional[Any] , __lowerCamelCase : int=3 , __lowerCamelCase : Dict=64 , __lowerCamelCase : str=[256, 512, 1024, 2048] , __lowerCamelCase : str=[3, 4, 6, 3] , __lowerCamelCase : Optional[int]="bottleneck" , __lowerCamelCase : int="relu" , __lowerCamelCase : List[str]=False , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : int=None , **__lowerCamelCase : Dict , ): super().__init__(**__lowerCamelCase ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embedding_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = downsample_in_first_stage SCREAMING_SNAKE_CASE = ["stem"] + [f"stage{idx}" for idx in range(1 , len(__lowerCamelCase ) + 1 )] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__lowerCamelCase , out_indices=__lowerCamelCase , stage_names=self.stage_names ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = version.parse("1.11" ) @property def _snake_case ( self : Optional[int] ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _snake_case ( self : Optional[int] ): return 1e-3
698
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Dict = { 'configuration_bigbird_pegasus': [ 'BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BigBirdPegasusConfig', 'BigBirdPegasusOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST', 'BigBirdPegasusForCausalLM', 'BigBirdPegasusForConditionalGeneration', 'BigBirdPegasusForQuestionAnswering', 'BigBirdPegasusForSequenceClassification', 'BigBirdPegasusModel', 'BigBirdPegasusPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __A : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
706
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType __A : str = logging.get_logger(__name__) __A : Optional[Any] = { 'openai/imagegpt-small': '', 'openai/imagegpt-medium': '', 'openai/imagegpt-large': '', } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "imagegpt" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , __lowerCamelCase : Any=512 + 1 , __lowerCamelCase : str=32 * 32 , __lowerCamelCase : Any=512 , __lowerCamelCase : Optional[int]=24 , __lowerCamelCase : Tuple=8 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]="quick_gelu" , __lowerCamelCase : int=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=1e-5 , __lowerCamelCase : Optional[Any]=0.02 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : List[Any]=False , __lowerCamelCase : int=False , __lowerCamelCase : int=False , **__lowerCamelCase : Union[str, Any] , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_embd SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = tie_word_embeddings super().__init__(tie_word_embeddings=__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Optional[Any] ): return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ] ) def _snake_case ( self : Optional[int] , __lowerCamelCase : "FeatureExtractionMixin" , __lowerCamelCase : int = 1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 32 , __lowerCamelCase : int = 32 , ): SCREAMING_SNAKE_CASE = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = dict(preprocessor(images=__lowerCamelCase , return_tensors=__lowerCamelCase ) ) return inputs
698
0
from __future__ import annotations import math def __a ( A__ : float , A__ : int ): SCREAMING_SNAKE_CASE = u for i in range(1 , A__ ): SCREAMING_SNAKE_CASE = temp * (u - i) return temp def __a ( ): SCREAMING_SNAKE_CASE = int(input("enter the numbers of values: " ) ) SCREAMING_SNAKE_CASE = [] for _ in range(A__ ): y.append([] ) for i in range(A__ ): for j in range(A__ ): y[i].append(A__ ) SCREAMING_SNAKE_CASE = 0 print("enter the values of parameters in a list: " ) SCREAMING_SNAKE_CASE = list(map(A__ , input().split() ) ) print("enter the values of corresponding parameters: " ) for i in range(A__ ): SCREAMING_SNAKE_CASE = float(input() ) SCREAMING_SNAKE_CASE = int(input("enter the value to interpolate: " ) ) SCREAMING_SNAKE_CASE = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , A__ ): for j in range(n - i ): SCREAMING_SNAKE_CASE = y[j + 1][i - 1] - y[j][i - 1] SCREAMING_SNAKE_CASE = y[0][0] for i in range(1 , A__ ): summ += (ucal(A__ , A__ ) * y[0][i]) / math.factorial(A__ ) print(F"the value at {value} is {summ}" ) if __name__ == "__main__": main()
707
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @slow @require_torch def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("bert-base-uncased" ) SCREAMING_SNAKE_CASE = bertabert.config.encoder.vocab_size SCREAMING_SNAKE_CASE = tokenizer.sep_token_id SCREAMING_SNAKE_CASE = tokenizer.cls_token_id SCREAMING_SNAKE_CASE = 128 SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) SCREAMING_SNAKE_CASE = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) SCREAMING_SNAKE_CASE = train_dataset.select(range(32 ) ) SCREAMING_SNAKE_CASE = val_dataset.select(range(16 ) ) SCREAMING_SNAKE_CASE = 4 def _map_to_encoder_decoder_inputs(__lowerCamelCase : str ): # Tokenizer will automatically set [BOS] <text> [EOS] SCREAMING_SNAKE_CASE = tokenizer(batch["article"] , padding="max_length" , truncation=__lowerCamelCase , max_length=512 ) SCREAMING_SNAKE_CASE = tokenizer(batch["highlights"] , padding="max_length" , truncation=__lowerCamelCase , max_length=128 ) SCREAMING_SNAKE_CASE = inputs.input_ids SCREAMING_SNAKE_CASE = inputs.attention_mask SCREAMING_SNAKE_CASE = outputs.input_ids SCREAMING_SNAKE_CASE = outputs.input_ids.copy() SCREAMING_SNAKE_CASE = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] SCREAMING_SNAKE_CASE = outputs.attention_mask assert all(len(__lowerCamelCase ) == 512 for x in inputs.input_ids ) assert all(len(__lowerCamelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(__lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = pred.label_ids SCREAMING_SNAKE_CASE = pred.predictions # all unnecessary tokens are removed SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) SCREAMING_SNAKE_CASE = sum([int(pred_str[i] == label_str[i] ) for i in range(len(__lowerCamelCase ) )] ) / len(__lowerCamelCase ) return {"accuracy": accuracy} # map train dataset SCREAMING_SNAKE_CASE = train_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset SCREAMING_SNAKE_CASE = val_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCamelCase , batch_size=__lowerCamelCase , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE = SeqaSeqTrainingArguments( output_dir=__lowerCamelCase , per_device_train_batch_size=__lowerCamelCase , per_device_eval_batch_size=__lowerCamelCase , predict_with_generate=__lowerCamelCase , evaluation_strategy="steps" , do_train=__lowerCamelCase , do_eval=__lowerCamelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer SCREAMING_SNAKE_CASE = SeqaSeqTrainer( model=__lowerCamelCase , args=__lowerCamelCase , compute_metrics=_compute_metrics , train_dataset=__lowerCamelCase , eval_dataset=__lowerCamelCase , tokenizer=__lowerCamelCase , ) # start training trainer.train()
698
0
from __future__ import annotations import numpy as np def __a ( A__ : np.ndarray ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = np.shape(A__ ) if rows != columns: SCREAMING_SNAKE_CASE = ( "'table' has to be of square shaped array but got a " F"{rows}x{columns} array:\n{table}" ) raise ValueError(A__ ) SCREAMING_SNAKE_CASE = np.zeros((rows, columns) ) SCREAMING_SNAKE_CASE = np.zeros((rows, columns) ) for i in range(A__ ): for j in range(A__ ): SCREAMING_SNAKE_CASE = sum(lower[i][k] * upper[k][j] for k in range(A__ ) ) if upper[j][j] == 0: raise ArithmeticError("No LU decomposition exists" ) SCREAMING_SNAKE_CASE = (table[i][j] - total) / upper[j][j] SCREAMING_SNAKE_CASE = 1 for j in range(A__ , A__ ): SCREAMING_SNAKE_CASE = sum(lower[i][k] * upper[k][j] for k in range(A__ ) ) SCREAMING_SNAKE_CASE = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
708
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, 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 ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , "num_attention_heads" ) ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : Optional[int]=64 , __lowerCamelCase : Dict=3 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : int=2 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Tuple=[128, 256, 384] , __lowerCamelCase : int=[4, 6, 8] , __lowerCamelCase : Tuple=[2, 3, 4] , __lowerCamelCase : List[str]=[16, 16, 16] , __lowerCamelCase : int=0 , __lowerCamelCase : List[Any]=[2, 2, 2] , __lowerCamelCase : List[str]=[2, 2, 2] , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=True , __lowerCamelCase : int=2 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = kernel_size SCREAMING_SNAKE_CASE = stride SCREAMING_SNAKE_CASE = padding SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = [ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[str] ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Any ): SCREAMING_SNAKE_CASE = LevitModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) SCREAMING_SNAKE_CASE = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def _snake_case ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = LevitForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) lowerCamelCase__ = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = LevitModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : Any ): return @unittest.skip(reason="Levit does not use inputs_embeds" ) def _snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason="Levit does not support input and output embeddings" ) def _snake_case ( self : Tuple ): pass @unittest.skip(reason="Levit does not output attentions" ) def _snake_case ( self : Tuple ): pass def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : List[Any] ): def check_hidden_states_output(__lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = len(self.model_tester.depths ) + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) SCREAMING_SNAKE_CASE = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : int ): pass def _snake_case ( self : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : int=False ): SCREAMING_SNAKE_CASE = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def _snake_case ( self : List[Any] ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(__lowerCamelCase ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(__lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.gradient_checkpointing_enable() model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss loss.backward() def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(__lowerCamelCase ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}" ): SCREAMING_SNAKE_CASE = problem_type["title"] SCREAMING_SNAKE_CASE = problem_type["num_labels"] SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() SCREAMING_SNAKE_CASE = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) SCREAMING_SNAKE_CASE = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=__lowerCamelCase ) as warning_list: SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def _snake_case ( self : List[Any] ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = LevitModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Dict ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __lowerCamelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([1.0_448, -0.3_745, -1.8_317] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
698
0
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": __A : List[str] = pd.read_csv('sample_data.csv', header=None) __A : List[Any] = df.shape[:1][0] # If you're using some other dataset input the target column __A : Tuple = df.iloc[:, 1:2] __A : List[str] = actual_data.values.reshape(len_data, 1) __A : Tuple = MinMaxScaler().fit_transform(actual_data) __A : Any = 1_0 __A : Any = 5 __A : Union[str, Any] = 2_0 __A : str = len_data - periods * look_back __A : Optional[Any] = actual_data[:division] __A : str = actual_data[division - look_back :] __A : Tuple = [], [] __A : List[str] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) __A : Optional[Any] = np.array(train_x) __A : Any = np.array(test_x) __A : Optional[int] = np.array([list(i.ravel()) for i in train_y]) __A : Dict = np.array([list(i.ravel()) for i in test_y]) __A : Optional[Any] = Sequential() model.add(LSTM(1_2_8, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(6_4, input_shape=(1_2_8, 1))) model.add(Dense(forward_days)) model.compile(loss='mean_squared_error', optimizer='adam') __A : Union[str, Any] = model.fit( x_train, y_train, epochs=1_5_0, verbose=1, shuffle=True, batch_size=4 ) __A : str = model.predict(x_test)
709
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): return None class _SCREAMING_SNAKE_CASE : '''simple docstring''' def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : int ): return None class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = [ # (model_name, model_kwargs) ("bert-base-cased", {}), ("gpt2", {"use_cache": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) @require_torch @slow def _snake_case ( self : Optional[int] ): from transformers import BertModel SCREAMING_SNAKE_CASE = ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"] with NamedTemporaryFile(mode="w+t" ) as vocab_file: vocab_file.write("\n".join(__lowerCamelCase ) ) vocab_file.flush() SCREAMING_SNAKE_CASE = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: SCREAMING_SNAKE_CASE = BertModel(BertConfig(vocab_size=len(__lowerCamelCase ) ) ) model.save_pretrained(__lowerCamelCase ) self._test_export(__lowerCamelCase , "pt" , 12 , __lowerCamelCase ) @require_tf @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "tf" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(Path(__lowerCamelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) @require_torch @slow def _snake_case ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE = self._test_export(__lowerCamelCase , "pt" , 12 , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = quantize(__lowerCamelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__lowerCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) def _snake_case ( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Tuple=None , **__lowerCamelCase : List[str] ): try: # Compute path with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE = Path(__lowerCamelCase ).joinpath("model.onnx" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) return path except Exception as e: self.fail(__lowerCamelCase ) @require_torch @require_tokenizers @slow def _snake_case ( self : Dict ): from transformers import BertModel SCREAMING_SNAKE_CASE = BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "pt" ) @require_tf @require_tokenizers @slow def _snake_case ( self : int ): from transformers import TFBertModel SCREAMING_SNAKE_CASE = TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__lowerCamelCase , __lowerCamelCase , "tf" ) def _snake_case ( self : int , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = FeatureExtractionPipeline(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = infer_shapes(__lowerCamelCase , __lowerCamelCase ) # Assert all variables are present self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __lowerCamelCase ) self.assertSequenceEqual(variable_names[3:] , __lowerCamelCase ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: "batch", 1: "sequence"} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["output_0"] , {0: "batch", 1: "sequence"} ) self.assertDictEqual(shapes["output_1"] , {0: "batch"} ) def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask", "token_type_ids"] SCREAMING_SNAKE_CASE = {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__lowerCamelCase ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__lowerCamelCase ) , set(__lowerCamelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__lowerCamelCase , (tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ensure_valid_input(FuncNonContiguousArgs() , __lowerCamelCase , __lowerCamelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__lowerCamelCase ) , 1 ) self.assertEqual(len(__lowerCamelCase ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["input_ids"] ) self.assertEqual(ordered_input_names[0] , "input_ids" ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = generate_identified_filename(Path("/home/something/my_fake_model.onnx" ) , "-test" ) self.assertEqual("/home/something/my_fake_model-test.onnx" , generated.as_posix() )
698
0
def __a ( A__ : list[list] ): SCREAMING_SNAKE_CASE = current_set.copy() for row_index, row in enumerate(A__ ): SCREAMING_SNAKE_CASE = row[0] for column_index, column in enumerate(A__ ): if magnitude == 0: SCREAMING_SNAKE_CASE = column continue SCREAMING_SNAKE_CASE = column / magnitude # Subtract to cancel term SCREAMING_SNAKE_CASE = current_set[0] SCREAMING_SNAKE_CASE = [first_row] SCREAMING_SNAKE_CASE = current_set[1::] for row in current_set: SCREAMING_SNAKE_CASE = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(A__ ) continue for column_index in range(len(A__ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(A__ ) # Create next recursion iteration set if len(final_set[0] ) != 3: SCREAMING_SNAKE_CASE = final_set[0] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) SCREAMING_SNAKE_CASE = simplify(A__ ) for i in range(len(A__ ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , A__ ) SCREAMING_SNAKE_CASE = resultant return final_set def __a ( A__ : list[list] ): if len(A__ ) == 0: raise IndexError("solve_simultaneous() requires n lists of length n+1" ) SCREAMING_SNAKE_CASE = len(A__ ) + 1 if any(len(A__ ) != _length for item in equations ): raise IndexError("solve_simultaneous() requires n lists of length n+1" ) for row in equations: if any(not isinstance(A__ , (int, float) ) for column in row ): raise ValueError("solve_simultaneous() requires lists of integers" ) if len(A__ ) == 1: return [equations[0][-1] / equations[0][0]] SCREAMING_SNAKE_CASE = equations.copy() if any(0 in row for row in data_set ): SCREAMING_SNAKE_CASE = data_set.copy() SCREAMING_SNAKE_CASE = [] for row_index, row in enumerate(A__ ): if 0 not in row: SCREAMING_SNAKE_CASE = data_set.pop(A__ ) break if not full_row: raise ValueError("solve_simultaneous() requires at least 1 full equation" ) data_set.insert(0 , A__ ) SCREAMING_SNAKE_CASE = data_set.copy() SCREAMING_SNAKE_CASE = simplify(A__ ) SCREAMING_SNAKE_CASE = simplified[::-1] SCREAMING_SNAKE_CASE = [] for row in simplified: SCREAMING_SNAKE_CASE = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue SCREAMING_SNAKE_CASE = row.copy()[: len(A__ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(A__ ) == 0: solutions.append(0 ) continue SCREAMING_SNAKE_CASE = temp_row[1::] SCREAMING_SNAKE_CASE = temp_row[::-1] for column_index, column in enumerate(A__ ): current_solution -= column * solutions[column_index] solutions.append(A__ ) SCREAMING_SNAKE_CASE = [] for item in solutions: final.append(float(round(A__ , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() __A : Union[str, Any] = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
710
from manim import * class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = VGroup(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("CPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("GPU" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Model" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): rect.set_stroke(__lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) SCREAMING_SNAKE_CASE = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__lowerCamelCase , buff=0.0 ) self.add(__lowerCamelCase ) cpu_targs.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) SCREAMING_SNAKE_CASE = Text("Loaded Checkpoint" , font_size=24 ) SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , aligned_edge=__lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) SCREAMING_SNAKE_CASE = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = MarkupText( f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(__lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) SCREAMING_SNAKE_CASE = MarkupText( f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__lowerCamelCase ) , Write(__lowerCamelCase ) ) self.play(Write(__lowerCamelCase , run_time=1 ) , Create(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__lowerCamelCase ): SCREAMING_SNAKE_CASE = fill.copy().set_fill(__lowerCamelCase , opacity=0.7 ) target.move_to(__lowerCamelCase ) first_animations.append(GrowFromCenter(__lowerCamelCase , run_time=1 ) ) SCREAMING_SNAKE_CASE = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__lowerCamelCase , run_time=1.5 ) ) self.play(*__lowerCamelCase ) self.play(*__lowerCamelCase ) self.wait()
698
0
# 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 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __a ( A__ : str=None ): if subparsers is not None: SCREAMING_SNAKE_CASE = subparsers.add_parser("test" ) else: SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=A__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=A__ ) return parser def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: SCREAMING_SNAKE_CASE = script_name else: SCREAMING_SNAKE_CASE = F"--config_file={args.config_file} {script_name}" SCREAMING_SNAKE_CASE = ["accelerate-launch"] + test_args.split() SCREAMING_SNAKE_CASE = execute_subprocess_async(A__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __a ( ): SCREAMING_SNAKE_CASE = test_command_parser() SCREAMING_SNAKE_CASE = parser.parse_args() test_command(A__ ) if __name__ == "__main__": main()
711
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 import ANY if is_vision_available(): from PIL import Image else: class _SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _snake_case ( *__lowerCamelCase : Any , **__lowerCamelCase : Any ): pass @is_pipeline_test @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @require_torch def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowerCamelCase ) , [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @require_tf def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, {"score": 0.333, "label": ANY(__lowerCamelCase )}, ], ] , ) @slow @require_torch def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE = image_classifier(__lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , )
698
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : Optional[Any] = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json' ), } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "dpr" def __init__( self : List[str] , __lowerCamelCase : List[Any]=30522 , __lowerCamelCase : Optional[Any]=768 , __lowerCamelCase : Union[str, Any]=12 , __lowerCamelCase : int=12 , __lowerCamelCase : int=3072 , __lowerCamelCase : int="gelu" , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Optional[int]=512 , __lowerCamelCase : str=2 , __lowerCamelCase : Tuple=0.02 , __lowerCamelCase : Tuple=1e-12 , __lowerCamelCase : int=0 , __lowerCamelCase : Optional[Any]="absolute" , __lowerCamelCase : int = 0 , **__lowerCamelCase : Optional[Any] , ): super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = position_embedding_type
712
__A : dict[str, float] = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.6_0217_6634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def __a ( A__ : str , A__ : str , A__ : float ): if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: SCREAMING_SNAKE_CASE = ( F"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" F"Valid values are: {', '.join(A__ )}" ) raise ValueError(A__ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
698
0
'''simple docstring''' __A : Optional[Any] = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} __A : Optional[Any] = ['a', 'b', 'c', 'd', 'e'] def __a ( A__ : Dict , A__ : List[Any] , A__ : Optional[Any] ): SCREAMING_SNAKE_CASE = start # add current to visited visited.append(A__ ) SCREAMING_SNAKE_CASE = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: SCREAMING_SNAKE_CASE = topological_sort(A__ , A__ , A__ ) # if all neighbors visited add current to sort sort.append(A__ ) # if all vertices haven't been visited select a new one to visit if len(A__ ) != len(A__ ): for vertice in vertices: if vertice not in visited: SCREAMING_SNAKE_CASE = topological_sort(A__ , A__ , A__ ) # return sort return sort if __name__ == "__main__": __A : Any = topological_sort('a', [], []) print(sort)
713
from collections import deque from .hash_table import HashTable class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : Optional[int] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Optional[Any] ): super().__init__(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : Any , __lowerCamelCase : Dict , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.values[key] def _snake_case ( self : Union[str, Any] ): return ( sum(self.charge_factor - len(__lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__lowerCamelCase ) == 0 ): return key return super()._collision_resolution(__lowerCamelCase , __lowerCamelCase )
698
0
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __A : str = abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def __a ( A__ : Any ): config.addinivalue_line( "markers" , "is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested" ) config.addinivalue_line( "markers" , "is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested" ) config.addinivalue_line("markers" , "is_pipeline_test: mark test to run only when pipelines are tested" ) config.addinivalue_line("markers" , "is_staging_test: mark test to run only in the staging environment" ) config.addinivalue_line("markers" , "accelerate_tests: mark test that require accelerate" ) config.addinivalue_line("markers" , "tool_tests: mark the tool tests that are run on their specific schedule" ) def __a ( A__ : Union[str, Any] ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(A__ ) def __a ( A__ : List[Any] ): from transformers.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(A__ , id=A__ ) def __a ( A__ : Dict , A__ : List[str] ): # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: SCREAMING_SNAKE_CASE = 0 # Doctest custom flag to ignore output. __A : List[str] = doctest.register_optionflag('IGNORE_RESULT') __A : Any = doctest.OutputChecker class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def _snake_case ( self : Dict , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) __A : Tuple = CustomOutputChecker __A : Union[str, Any] = HfDoctestModule __A : Tuple = HfDocTestParser
714
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : int = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "gpt_neo" lowerCamelCase__ = ["past_key_values"] lowerCamelCase__ = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : str , __lowerCamelCase : Dict=50257 , __lowerCamelCase : Tuple=2048 , __lowerCamelCase : Optional[Any]=2048 , __lowerCamelCase : int=24 , __lowerCamelCase : int=[[["global", "local"], 12]] , __lowerCamelCase : int=16 , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[Any]=256 , __lowerCamelCase : Tuple="gelu_new" , __lowerCamelCase : Optional[Any]=0.0 , __lowerCamelCase : str=0.0 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[Any]=1e-5 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Dict=True , __lowerCamelCase : Dict=50256 , __lowerCamelCase : Optional[int]=50256 , **__lowerCamelCase : Dict , ): SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_layers SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = window_size SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_dropout SCREAMING_SNAKE_CASE = embed_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = classifier_dropout SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id SCREAMING_SNAKE_CASE = attention_types SCREAMING_SNAKE_CASE = self.expand_attention_types_params(__lowerCamelCase ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " f"`config.num_layers = {self.num_layers}`. " "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) @staticmethod def _snake_case ( __lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __a ( A__ : str , A__ : List[Any] , A__ : List[str] , A__ : Union[str, Any] ): import torch SCREAMING_SNAKE_CASE = input.size() SCREAMING_SNAKE_CASE = len(A__ ) SCREAMING_SNAKE_CASE = shape[dimension] SCREAMING_SNAKE_CASE = torch.arange(0 , A__ , A__ ) SCREAMING_SNAKE_CASE = torch.div(sizedim - size , A__ , rounding_mode="floor" ) + 1 SCREAMING_SNAKE_CASE = torch.arange(A__ ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE = [slice(A__ )] * rank SCREAMING_SNAKE_CASE = indices SCREAMING_SNAKE_CASE = input[s] SCREAMING_SNAKE_CASE = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(A__ ) def __a ( A__ : Union[str, Any] , A__ : Optional[int] ): import torch SCREAMING_SNAKE_CASE = torch.arange(1 , A__ ) SCREAMING_SNAKE_CASE = torch.remainder(A__ , A__ ) SCREAMING_SNAKE_CASE = remainders == 0 SCREAMING_SNAKE_CASE = candidates[divisor_indices] SCREAMING_SNAKE_CASE = torch.max(A__ ) return largest_divisor, torch.div(A__ , A__ , rounding_mode="floor" ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' @property def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__lowerCamelCase , direction="inputs" ) SCREAMING_SNAKE_CASE = {0: "batch", 1: "past_sequence + sequence"} else: SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return common_inputs @property def _snake_case ( self : Optional[int] ): return self._config.num_heads def _snake_case ( self : Union[str, Any] , __lowerCamelCase : PreTrainedTokenizer , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[TensorType] = None , ): SCREAMING_SNAKE_CASE = super(__lowerCamelCase , self ).generate_dummy_inputs( __lowerCamelCase , batch_size=__lowerCamelCase , seq_length=__lowerCamelCase , is_pair=__lowerCamelCase , framework=__lowerCamelCase ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = common_inputs["input_ids"].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE = seqlen + 2 SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE = [ (torch.zeros(__lowerCamelCase ), torch.zeros(__lowerCamelCase )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE = common_inputs["attention_mask"] if self.use_past: SCREAMING_SNAKE_CASE = ordered_inputs["attention_mask"].dtype SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__lowerCamelCase , __lowerCamelCase , dtype=__lowerCamelCase )] , dim=1 ) return ordered_inputs @property def _snake_case ( self : Optional[int] ): return 13
698
0
import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Any , __lowerCamelCase : Dict=2 , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Dict=64 , __lowerCamelCase : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = np.random.default_rng(__lowerCamelCase ) SCREAMING_SNAKE_CASE = length SCREAMING_SNAKE_CASE = rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self : Tuple ): return self.length def __getitem__( self : List[Any] , __lowerCamelCase : Optional[Any] ): return {"x": self.x[i], "y": self.y[i]} class _SCREAMING_SNAKE_CASE ( torch.nn.Module ): '''simple docstring''' def __init__( self : List[str] , __lowerCamelCase : Dict=0 , __lowerCamelCase : Tuple=0 , __lowerCamelCase : Union[str, Any]=False ): super().__init__() SCREAMING_SNAKE_CASE = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE = True def _snake_case ( self : int , __lowerCamelCase : str=None ): if self.first_batch: print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}" ) SCREAMING_SNAKE_CASE = False return x * self.a[0] + self.b[0] class _SCREAMING_SNAKE_CASE ( torch.nn.Module ): '''simple docstring''' def __init__( self : str , __lowerCamelCase : Dict=0 , __lowerCamelCase : int=0 , __lowerCamelCase : Dict=False ): super().__init__() SCREAMING_SNAKE_CASE = torch.nn.Parameter(torch.tensor(__lowerCamelCase ).float() ) SCREAMING_SNAKE_CASE = torch.nn.Parameter(torch.tensor(__lowerCamelCase ).float() ) SCREAMING_SNAKE_CASE = True def _snake_case ( self : List[Any] , __lowerCamelCase : Dict=None ): if self.first_batch: print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}" ) SCREAMING_SNAKE_CASE = False return x * self.a + self.b def __a ( A__ : List[Any] , A__ : int = 16 ): from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"} SCREAMING_SNAKE_CASE = load_dataset("csv" , data_files=A__ ) SCREAMING_SNAKE_CASE = datasets["train"].unique("label" ) SCREAMING_SNAKE_CASE = {v: i for i, v in enumerate(A__ )} def tokenize_function(A__ : List[Any] ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer( examples["sentence1"] , examples["sentence2"] , truncation=A__ , max_length=A__ , padding="max_length" ) if "label" in examples: SCREAMING_SNAKE_CASE = [label_to_id[l] for l in examples["label"]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE = datasets.map( A__ , batched=A__ , remove_columns=["sentence1", "sentence2", "label"] , ) def collate_fn(A__ : Union[str, Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(A__ , padding="max_length" , max_length=128 , return_tensors="pt" ) return tokenizer.pad(A__ , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader(tokenized_datasets["train"] , shuffle=A__ , collate_fn=A__ , batch_size=2 ) SCREAMING_SNAKE_CASE = DataLoader(tokenized_datasets["validation"] , shuffle=A__ , collate_fn=A__ , batch_size=1 ) return train_dataloader, eval_dataloader
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __A : Any = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
698
0
from __future__ import annotations from collections import Counter from random import random class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] ): SCREAMING_SNAKE_CASE = {} def _snake_case ( self : str , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = {} def _snake_case ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : float ): if nodea not in self.connections: self.add_node(__lowerCamelCase ) if nodea not in self.connections: self.add_node(__lowerCamelCase ) SCREAMING_SNAKE_CASE = probability def _snake_case ( self : Optional[Any] ): return list(self.connections ) def _snake_case ( self : Tuple , __lowerCamelCase : str ): SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def __a ( A__ : str , A__ : list[tuple[str, str, float]] , A__ : int ): SCREAMING_SNAKE_CASE = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(A__ , A__ , A__ ) SCREAMING_SNAKE_CASE = Counter(graph.get_nodes() ) SCREAMING_SNAKE_CASE = start for _ in range(A__ ): SCREAMING_SNAKE_CASE = graph.transition(A__ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
716
import cmath import math def __a ( A__ : float , A__ : float , A__ : float , A__ : float ): SCREAMING_SNAKE_CASE = math.radians(A__ ) SCREAMING_SNAKE_CASE = math.radians(A__ ) # Convert voltage and current to rectangular form SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) SCREAMING_SNAKE_CASE = cmath.rect(A__ , A__ ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
698
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __A : Any = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
717
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def __a ( A__ : List[str] ): SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(A__ , A__ ) def __a ( A__ : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(A__ , A__ , bias=A__ ) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def __a ( A__ : Tuple , A__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = {} for old_key in state_dict.keys(): SCREAMING_SNAKE_CASE = old_key if "moe_layer.experts." in key: if expert_idx is not None: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts.0" , F"ffn.experts.expert_{expert_idx}" ) else: SCREAMING_SNAKE_CASE = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: SCREAMING_SNAKE_CASE = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: SCREAMING_SNAKE_CASE = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: SCREAMING_SNAKE_CASE = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: SCREAMING_SNAKE_CASE = key.replace("final_layer_norm" , "ff_layer_norm" ) SCREAMING_SNAKE_CASE = state_dict[old_key] return new_dict def __a ( A__ : List[str] , A__ : List[Any] , A__ : str , A__ : Union[str, Any] , A__ : str = WEIGHTS_NAME ): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 os.makedirs(A__ , exist_ok=A__ ) for expert in range(A__ ): SCREAMING_SNAKE_CASE = switch_checkpoint_path + F"-rank-{expert}.pt" if os.path.isfile(A__ ): SCREAMING_SNAKE_CASE = torch.load(A__ )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = os.path.join( A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) torch.save(A__ , A__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A__ )[0]].dtype ) # Add the last block SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{len(A__ )+1:05d}-of-???.bin" ) ) SCREAMING_SNAKE_CASE = torch.load(switch_checkpoint_path + "-shared.pt" )["model"] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE = rename_fairseq_keys(A__ , A__ ) SCREAMING_SNAKE_CASE = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A__ ) == 1: SCREAMING_SNAKE_CASE = os.path.join(A__ , A__ ) torch.save(A__ , A__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A__ , A__ ) # Otherwise, let's build the index SCREAMING_SNAKE_CASE = {} for idx, shard in enumerate(A__ ): SCREAMING_SNAKE_CASE = weights_name.replace(".bin" , F"-{idx+1:05d}-of-{len(A__ ):05d}.bin" ) SCREAMING_SNAKE_CASE = os.path.join(A__ , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(A__ , os.path.join(A__ , A__ ) ) for key in shard: SCREAMING_SNAKE_CASE = shard_file # Add the metadata SCREAMING_SNAKE_CASE = {"total_size": total_size} SCREAMING_SNAKE_CASE = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(A__ , A__ ) , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE = json.dumps(A__ , indent=2 , sort_keys=A__ ) + "\n" f.write(A__ ) return metadata, index if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) __A : Optional[int] = parser.parse_args() __A , __A : Union[str, Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_2_8, args.dtype, ) __A : Any = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8 ) config.save_pretrained(args.pytorch_dump_folder_path) __A : Any = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
698
0
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration __A : str = 5_0_0_0_0 __A : Optional[Any] = 5_0_0_0 __A : Union[str, Any] = os.path.split(__file__) __A : int = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def __a ( A__ : datasets.Dataset , A__ : Union[str, Any] ): for i in range(A__ ): SCREAMING_SNAKE_CASE = dataset[i] @get_duration def __a ( A__ : datasets.Dataset , A__ : Optional[int] , A__ : Tuple ): for i in range(0 , len(A__ ) , A__ ): SCREAMING_SNAKE_CASE = dataset[i : i + batch_size] @get_duration def __a ( A__ : datasets.Dataset , A__ : List[Any] , A__ : str ): with dataset.formatted_as(type=A__ ): for i in range(A__ ): SCREAMING_SNAKE_CASE = dataset[i] @get_duration def __a ( A__ : datasets.Dataset , A__ : Optional[Any] , A__ : Optional[Any] , A__ : Union[str, Any] ): with dataset.formatted_as(type=A__ ): for i in range(0 , A__ , A__ ): SCREAMING_SNAKE_CASE = dataset[i : i + batch_size] def __a ( ): SCREAMING_SNAKE_CASE = {"num examples": SPEED_TEST_N_EXAMPLES} SCREAMING_SNAKE_CASE = [ (read, {"length": SMALL_TEST}), (read, {"length": SPEED_TEST_N_EXAMPLES}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 10}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 100}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1000}), (read_formatted, {"type": "numpy", "length": SMALL_TEST}), (read_formatted, {"type": "pandas", "length": SMALL_TEST}), (read_formatted, {"type": "torch", "length": SMALL_TEST}), (read_formatted, {"type": "tensorflow", "length": SMALL_TEST}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 10}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1000}), ] SCREAMING_SNAKE_CASE = [ (read, {"length": SMALL_TEST}), (read, {"length": SPEED_TEST_N_EXAMPLES}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 10}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 100}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1000}), (read_formatted, {"type": "numpy", "length": SMALL_TEST}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 10}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print("generating dataset" ) SCREAMING_SNAKE_CASE = datasets.Features( {"list": datasets.Sequence(datasets.Value("float32" ) ), "numbers": datasets.Value("float32" )} ) SCREAMING_SNAKE_CASE = generate_example_dataset( os.path.join(A__ , "dataset.arrow" ) , A__ , num_examples=A__ , seq_shapes={"list": (100,)} , ) print("first set of iterations" ) for func, kwargs in functions: print(func.__name__ , str(A__ ) ) SCREAMING_SNAKE_CASE = func(A__ , **A__ ) print("shuffling dataset" ) SCREAMING_SNAKE_CASE = dataset.shuffle() print("Second set of iterations (after shuffling" ) for func, kwargs in functions_shuffled: print("shuffled " , func.__name__ , str(A__ ) ) SCREAMING_SNAKE_CASE = func( A__ , **A__ ) with open(A__ , "wb" ) as f: f.write(json.dumps(A__ ).encode("utf-8" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
718
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = BlipImageProcessor() SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" ) SCREAMING_SNAKE_CASE = BlipProcessor(__lowerCamelCase , __lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self : Dict , **__lowerCamelCase : Any ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).tokenizer def _snake_case ( self : List[Any] , **__lowerCamelCase : Optional[Any] ): return AutoProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ).image_processor def _snake_case ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__lowerCamelCase , padding_value=1.0 ) SCREAMING_SNAKE_CASE = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCamelCase ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = image_processor(__lowerCamelCase , return_tensors="np" ) SCREAMING_SNAKE_CASE = processor(images=__lowerCamelCase , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "lower newer" SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=__lowerCamelCase , images=__lowerCamelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
698
0