code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" def __A () ->Tuple: """simple docstring""" lowerCAmelCase__ :Any = [] lowerCAmelCase__ :str = 1 while len(_SCREAMING_SNAKE_CASE ) < 1e6: constant.append(str(_SCREAMING_SNAKE_CASE ) ) i += 1 lowerCAmelCase__ :Optional[Any] = ''.join(_SCREAMING_SNAKE_CASE ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
293
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
1
"""simple docstring""" import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __A (_SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) ->Optional[Any]: """simple docstring""" return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class _lowerCAmelCase : """simple docstring""" __magic_name__ :str = field( metadata={"""help""": """The csv file to plot."""} , ) __magic_name__ :bool = field( default=a , metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""} , ) __magic_name__ :bool = field( default=a , metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""} , ) __magic_name__ :bool = field( default=a , metadata={"""help""": """Disable logarithmic scale when plotting"""} , ) __magic_name__ :bool = field( default=a , metadata={ """help""": """Whether the csv file has training results or inference results. Defaults to inference results.""" } , ) __magic_name__ :Optional[str] = field( default=a , metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""} , ) __magic_name__ :Optional[List[str]] = list_field( default=a , metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""} ) def __A (_SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" try: int(_SCREAMING_SNAKE_CASE ) return True except ValueError: return False def __A (_SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" try: float(_SCREAMING_SNAKE_CASE ) return True except ValueError: return False class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = args lowerCAmelCase__ :int = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='' ) as csv_file: lowerCAmelCase__ :Optional[Any] = csv.DictReader(__UpperCAmelCase ) for row in reader: lowerCAmelCase__ :List[str] = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'] ) ) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'] ) ) if can_convert_to_int(row['result'] ): # value is not None lowerCAmelCase__ :List[str] = int(row['result'] ) elif can_convert_to_float(row['result'] ): # value is not None lowerCAmelCase__ :Optional[int] = float(row['result'] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :int = plt.subplots() lowerCAmelCase__ :List[str] = 'Time usage' if self.args.is_time else 'Memory usage' lowerCAmelCase__ :Tuple = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log' ) ax.set_yscale('log' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): lowerCAmelCase__ :List[str] = sorted(set(self.result_dict[model_name]['bsz'] ) ) lowerCAmelCase__ :List[Any] = sorted(set(self.result_dict[model_name]['seq_len'] ) ) lowerCAmelCase__ :Tuple = self.result_dict[model_name]['result'] ((lowerCAmelCase__) , (lowerCAmelCase__)) :str = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) lowerCAmelCase__ :int = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: lowerCAmelCase__ :List[str] = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=__UpperCAmelCase , ) else: lowerCAmelCase__ :List[str] = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((lowerCAmelCase__) , (lowerCAmelCase__)) :Optional[Any] = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) lowerCAmelCase__ :Tuple = np.asarray(__UpperCAmelCase , __UpperCAmelCase )[: len(__UpperCAmelCase )] plt.scatter( __UpperCAmelCase , __UpperCAmelCase , label=F"{label_model_name} - {inner_loop_label}: {inner_loop_value}" ) plt.plot(__UpperCAmelCase , __UpperCAmelCase , '--' ) title_str += F" {label_model_name} vs." lowerCAmelCase__ :int = title_str[:-4] lowerCAmelCase__ :Dict = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(__UpperCAmelCase ) plt.xlabel(__UpperCAmelCase ) plt.ylabel(__UpperCAmelCase ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __A () ->List[str]: """simple docstring""" lowerCAmelCase__ :List[Any] = HfArgumentParser(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = parser.parse_args_into_dataclasses()[0] lowerCAmelCase__ :Dict = Plot(args=_SCREAMING_SNAKE_CASE ) plot.plot() if __name__ == "__main__": main()
293
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], '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]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
1
"""simple docstring""" import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_COMMIT_HASH from huggingface_hub.utils import ( EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError, is_jinja_available, ) from packaging import version from requests import HTTPError from .. import __version__ from .constants import ( DEPRECATED_REVISION_ARGS, DIFFUSERS_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, ) from .import_utils import ( ENV_VARS_TRUE_VALUES, _flax_version, _jax_version, _onnxruntime_version, _torch_version, is_flax_available, is_onnx_available, is_torch_available, ) from .logging import get_logger __A = get_logger(__name__) __A = Path(__file__).parent / """model_card_template.md""" __A = uuida().hex __A = os.getenv("""HF_HUB_OFFLINE""", """""").upper() in ENV_VARS_TRUE_VALUES __A = os.getenv("""DISABLE_TELEMETRY""", """""").upper() in ENV_VARS_TRUE_VALUES __A = HUGGINGFACE_CO_RESOLVE_ENDPOINT + """/api/telemetry/""" def __A (_SCREAMING_SNAKE_CASE = None ) ->str: """simple docstring""" lowerCAmelCase__ :List[str] = F"diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}" if DISABLE_TELEMETRY or HF_HUB_OFFLINE: return ua + "; telemetry/off" if is_torch_available(): ua += F"; torch/{_torch_version}" if is_flax_available(): ua += F"; jax/{_jax_version}" ua += F"; flax/{_flax_version}" if is_onnx_available(): ua += F"; onnxruntime/{_onnxruntime_version}" # CI will set this value to True if os.environ.get('DIFFUSERS_IS_CI' , '' ).upper() in ENV_VARS_TRUE_VALUES: ua += "; is_ci/true" if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): ua += "; " + "; ".join(F"{k}/{v}" for k, v in user_agent.items() ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): ua += "; " + user_agent return ua def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None ) ->int: """simple docstring""" if token is None: lowerCAmelCase__ :Optional[int] = HfFolder.get_token() if organization is None: lowerCAmelCase__ :Optional[int] = whoami(_SCREAMING_SNAKE_CASE )['name'] return F"{username}/{model_id}" else: return F"{organization}/{model_id}" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if not is_jinja_available(): raise ValueError( 'Modelcard rendering is based on Jinja templates.' ' Please make sure to have `jinja` installed before using `create_model_card`.' ' To install it, please run `pip install Jinja2`.' ) if hasattr(_SCREAMING_SNAKE_CASE , 'local_rank' ) and args.local_rank not in [-1, 0]: return lowerCAmelCase__ :Optional[Any] = args.hub_token if hasattr(_SCREAMING_SNAKE_CASE , 'hub_token' ) else None lowerCAmelCase__ :Tuple = get_full_repo_name(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Tuple = ModelCard.from_template( card_data=ModelCardData( # Card metadata object that will be converted to YAML block language='en' , license='apache-2.0' , library_name='diffusers' , tags=[] , datasets=args.dataset_name , metrics=[] , ) , template_path=_SCREAMING_SNAKE_CASE , model_name=_SCREAMING_SNAKE_CASE , repo_name=_SCREAMING_SNAKE_CASE , dataset_name=args.dataset_name if hasattr(_SCREAMING_SNAKE_CASE , 'dataset_name' ) else None , learning_rate=args.learning_rate , train_batch_size=args.train_batch_size , eval_batch_size=args.eval_batch_size , gradient_accumulation_steps=( args.gradient_accumulation_steps if hasattr(_SCREAMING_SNAKE_CASE , 'gradient_accumulation_steps' ) else None ) , adam_betaa=args.adam_betaa if hasattr(_SCREAMING_SNAKE_CASE , 'adam_beta1' ) else None , adam_betaa=args.adam_betaa if hasattr(_SCREAMING_SNAKE_CASE , 'adam_beta2' ) else None , adam_weight_decay=args.adam_weight_decay if hasattr(_SCREAMING_SNAKE_CASE , 'adam_weight_decay' ) else None , adam_epsilon=args.adam_epsilon if hasattr(_SCREAMING_SNAKE_CASE , 'adam_epsilon' ) else None , lr_scheduler=args.lr_scheduler if hasattr(_SCREAMING_SNAKE_CASE , 'lr_scheduler' ) else None , lr_warmup_steps=args.lr_warmup_steps if hasattr(_SCREAMING_SNAKE_CASE , 'lr_warmup_steps' ) else None , ema_inv_gamma=args.ema_inv_gamma if hasattr(_SCREAMING_SNAKE_CASE , 'ema_inv_gamma' ) else None , ema_power=args.ema_power if hasattr(_SCREAMING_SNAKE_CASE , 'ema_power' ) else None , ema_max_decay=args.ema_max_decay if hasattr(_SCREAMING_SNAKE_CASE , 'ema_max_decay' ) else None , mixed_precision=args.mixed_precision , ) lowerCAmelCase__ :Tuple = os.path.join(args.output_dir , 'README.md' ) model_card.save(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) ->int: """simple docstring""" if resolved_file is None or commit_hash is not None: return commit_hash lowerCAmelCase__ :Any = str(Path(_SCREAMING_SNAKE_CASE ).as_posix() ) lowerCAmelCase__ :int = re.search(r'snapshots/([^/]+)/' , _SCREAMING_SNAKE_CASE ) if search is None: return None lowerCAmelCase__ :List[Any] = search.groups()[0] return commit_hash if REGEX_COMMIT_HASH.match(_SCREAMING_SNAKE_CASE ) else None # Old default cache path, potentially to be migrated. # This logic was more or less taken from `transformers`, with the following differences: # - Diffusers doesn't use custom environment variables to specify the cache path. # - There is no need to migrate the cache format, just move the files to the new location. __A = os.path.expanduser( os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface""")) ) __A = os.path.join(hf_cache_home, """diffusers""") def __A (_SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None ) ->None: """simple docstring""" if new_cache_dir is None: lowerCAmelCase__ :Optional[Any] = DIFFUSERS_CACHE if old_cache_dir is None: lowerCAmelCase__ :Tuple = old_diffusers_cache lowerCAmelCase__ :Optional[int] = Path(_SCREAMING_SNAKE_CASE ).expanduser() lowerCAmelCase__ :int = Path(_SCREAMING_SNAKE_CASE ).expanduser() for old_blob_path in old_cache_dir.glob('**/blobs/*' ): if old_blob_path.is_file() and not old_blob_path.is_symlink(): lowerCAmelCase__ :Any = new_cache_dir / old_blob_path.relative_to(_SCREAMING_SNAKE_CASE ) new_blob_path.parent.mkdir(parents=_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) os.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) try: os.symlink(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) except OSError: logger.warning( 'Could not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded.' ) # At this point, old_cache_dir contains symlinks to the new cache (it can still be used). __A = os.path.join(DIFFUSERS_CACHE, """version_diffusers_cache.txt""") if not os.path.isfile(cache_version_file): __A = 0 else: with open(cache_version_file) as f: try: __A = int(f.read()) except ValueError: __A = 0 if cache_version < 1: __A = os.path.isdir(old_diffusers_cache) and len(os.listdir(old_diffusers_cache)) > 0 if old_cache_is_not_empty: logger.warning( """The cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your """ """existing cached models. This is a one-time operation, you can interrupt it or run it """ """later by calling `diffusers.utils.hub_utils.move_cache()`.""" ) try: move_cache() except Exception as e: __A = """\n""".join(traceback.format_tb(e.__traceback__)) logger.error( F'''There was a problem when trying to move your cache:\n\n{trace}\n{e.__class__.__name__}: {e}\n\nPlease ''' """file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole """ """message and we will do our best to help.""" ) if cache_version < 1: try: os.makedirs(DIFFUSERS_CACHE, exist_ok=True) with open(cache_version_file, """w""") as f: f.write("""1""") except Exception: logger.warning( F'''There was a problem when trying to write in your cache folder ({DIFFUSERS_CACHE}). Please, ensure ''' """the directory exists and can be written to.""" ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) ->str: """simple docstring""" if variant is not None: lowerCAmelCase__ :int = weights_name.split('.' ) lowerCAmelCase__ :Optional[Any] = splits[:-1] + [variant] + splits[-1:] lowerCAmelCase__ :Tuple = '.'.join(_SCREAMING_SNAKE_CASE ) return weights_name def __A (_SCREAMING_SNAKE_CASE , *, _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , ) ->Dict: """simple docstring""" lowerCAmelCase__ :Optional[Any] = str(_SCREAMING_SNAKE_CASE ) if os.path.isfile(_SCREAMING_SNAKE_CASE ): return pretrained_model_name_or_path elif os.path.isdir(_SCREAMING_SNAKE_CASE ): if os.path.isfile(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ): # Load from a PyTorch checkpoint lowerCAmelCase__ :int = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return model_file elif subfolder is not None and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :Dict = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return model_file else: raise EnvironmentError( F"Error no file named {weights_name} found in directory {pretrained_model_name_or_path}." ) else: # 1. First check if deprecated way of loading from branches is used if ( revision in DEPRECATED_REVISION_ARGS and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME) and version.parse(version.parse(_SCREAMING_SNAKE_CASE ).base_version ) >= version.parse('0.20.0' ) ): try: lowerCAmelCase__ :Optional[int] = hf_hub_download( _SCREAMING_SNAKE_CASE , filename=_add_variant(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , cache_dir=_SCREAMING_SNAKE_CASE , force_download=_SCREAMING_SNAKE_CASE , proxies=_SCREAMING_SNAKE_CASE , resume_download=_SCREAMING_SNAKE_CASE , local_files_only=_SCREAMING_SNAKE_CASE , use_auth_token=_SCREAMING_SNAKE_CASE , user_agent=_SCREAMING_SNAKE_CASE , subfolder=_SCREAMING_SNAKE_CASE , revision=revision or commit_hash , ) warnings.warn( F"Loading the variant {revision} from {pretrained_model_name_or_path} via `revision='{revision}'` is deprecated. Loading instead from `revision='main'` with `variant={revision}`. Loading model variants via `revision='{revision}'` will be removed in diffusers v1. Please use `variant='{revision}'` instead." , _SCREAMING_SNAKE_CASE , ) return model_file except: # noqa: E722 warnings.warn( F"You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision='{revision}'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant='{revision}'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} file in the 'main' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title '{pretrained_model_name_or_path} is missing {_add_variant(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}' so that the correct variant file can be added." , _SCREAMING_SNAKE_CASE , ) try: # 2. Load model file as usual lowerCAmelCase__ :int = hf_hub_download( _SCREAMING_SNAKE_CASE , filename=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , force_download=_SCREAMING_SNAKE_CASE , proxies=_SCREAMING_SNAKE_CASE , resume_download=_SCREAMING_SNAKE_CASE , local_files_only=_SCREAMING_SNAKE_CASE , use_auth_token=_SCREAMING_SNAKE_CASE , user_agent=_SCREAMING_SNAKE_CASE , subfolder=_SCREAMING_SNAKE_CASE , revision=revision or commit_hash , ) return model_file except RepositoryNotFoundError: raise EnvironmentError( F"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier " 'listed on \'https://huggingface.co/models\'\nIf this is a private repository, make sure to pass a ' 'token having permission to this repo with `use_auth_token` or log in with `huggingface-cli ' 'login`.' ) except RevisionNotFoundError: raise EnvironmentError( F"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for " 'this model name. Check the model page at ' F"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions." ) except EntryNotFoundError: raise EnvironmentError( F"{pretrained_model_name_or_path} does not appear to have a file named {weights_name}." ) except HTTPError as err: raise EnvironmentError( F"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}" ) except ValueError: raise EnvironmentError( F"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it" F" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a" F" directory containing a file named {weights_name} or" ' \nCheckout your internet connection or see how to run the library in' ' offline mode at \'https://huggingface.co/docs/diffusers/installation#offline-mode\'.' ) except EnvironmentError: raise EnvironmentError( F"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from " '\'https://huggingface.co/models\', make sure you don\'t have a local directory with the same name. ' F"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory " F"containing a file named {weights_name}" )
293
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" lowerCAmelCase__ :Tuple = [1] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = 0, 0, 0 lowerCAmelCase__ :List[Any] = ugly_nums[ia] * 2 lowerCAmelCase__ :Tuple = ugly_nums[ia] * 3 lowerCAmelCase__ :int = ugly_nums[ia] * 5 for _ in range(1 , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ugly_nums.append(_SCREAMING_SNAKE_CASE ) if next_num == next_a: ia += 1 lowerCAmelCase__ :Union[str, Any] = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 lowerCAmelCase__ :Dict = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 lowerCAmelCase__ :Optional[Any] = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F'''{ugly_numbers(200) = }''')
293
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
1
"""simple docstring""" 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 (_SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" lowerCAmelCase__ :Dict = [ '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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->List[str]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = emb.weight.shape lowerCAmelCase__ :Optional[Any] = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :int = emb.weight.data return lin_layer def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) ->Any: """simple docstring""" lowerCAmelCase__ :Tuple = {} for old_key in state_dict.keys(): lowerCAmelCase__ :Optional[int] = old_key if "moe_layer.experts." in key: if expert_idx is not None: lowerCAmelCase__ :Optional[Any] = key.replace('moe_layer.experts.0' , F"ffn.experts.expert_{expert_idx}" ) else: lowerCAmelCase__ :Optional[Any] = key.replace('moe_layer.experts.' , 'ffn.experts.expert_' ) if "gate" in key: lowerCAmelCase__ :Any = key.replace('.moe_layer.gate.wg' , '.ffn.router.classifier' ) if "fc2" and "experts" not in key: lowerCAmelCase__ :List[Any] = key.replace('.fc2.' , '.ffn.fc2.' ) if "fc1" and "experts" not in key: lowerCAmelCase__ :List[str] = key.replace('.fc1.' , '.ffn.fc1.' ) if ".encoder_attn." in key: lowerCAmelCase__ :Dict = key.replace('.encoder_attn.' , '.cross_attention.' ) if "encoder_attn_layer_norm" in key: lowerCAmelCase__ :Union[str, Any] = key.replace('encoder_attn_layer_norm' , 'cross_attention_layer_norm' ) if "final_layer_norm" in key: lowerCAmelCase__ :Optional[Any] = key.replace('final_layer_norm' , 'ff_layer_norm' ) lowerCAmelCase__ :Tuple = state_dict[old_key] return new_dict def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = WEIGHTS_NAME ) ->int: """simple docstring""" lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = 0 os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) for expert in range(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Any = switch_checkpoint_path + F"-rank-{expert}.pt" if os.path.isfile(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :int = torch.load(_SCREAMING_SNAKE_CASE )['model'] remove_ignore_keys_(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = rename_fairseq_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = os.path.join( _SCREAMING_SNAKE_CASE , weights_name.replace('.bin' , F"-{len(_SCREAMING_SNAKE_CASE )+1:05d}-of-???.bin" ) ) torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) 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(_SCREAMING_SNAKE_CASE )[0]].dtype ) # Add the last block lowerCAmelCase__ :List[str] = os.path.join(_SCREAMING_SNAKE_CASE , weights_name.replace('.bin' , F"-{len(_SCREAMING_SNAKE_CASE )+1:05d}-of-???.bin" ) ) lowerCAmelCase__ :Dict = torch.load(switch_checkpoint_path + '-shared.pt' )['model'] remove_ignore_keys_(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = rename_fairseq_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 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(_SCREAMING_SNAKE_CASE ) == 1: lowerCAmelCase__ :Union[str, Any] = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Otherwise, let's build the index lowerCAmelCase__ :Dict = {} for idx, shard in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = weights_name.replace('.bin' , F"-{idx+1:05d}-of-{len(_SCREAMING_SNAKE_CASE ):05d}.bin" ) lowerCAmelCase__ :Dict = os.path.join(_SCREAMING_SNAKE_CASE , weights_name.replace('.bin' , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) for key in shard: lowerCAmelCase__ :int = shard_file # Add the metadata lowerCAmelCase__ :Tuple = {'total_size': total_size} lowerCAmelCase__ :Tuple = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 'w' , encoding='utf-8' ) as f: lowerCAmelCase__ :Union[str, Any] = json.dumps(_SCREAMING_SNAKE_CASE , indent=2 , sort_keys=_SCREAMING_SNAKE_CASE ) + '\n' f.write(_SCREAMING_SNAKE_CASE ) return metadata, index if __name__ == "__main__": __A = 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 = parser.parse_args() __A , __A = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) __A = NllbMoeConfig.from_pretrained( """facebook/nllb-200-3.3B""", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) __A = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print("""Done""") model.save_pretrained(args.pytorch_dump_folder_path)
293
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: __A = None __A = logging.get_logger(__name__) __A = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} __A = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json""" ), }, } __A = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } __A = """▁""" class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = VOCAB_FILES_NAMES __magic_name__ :Any = PRETRAINED_VOCAB_FILES_MAP __magic_name__ :Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ :Tuple = ["""input_ids""", """attention_mask"""] __magic_name__ :List[str] = BarthezTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="<s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="<s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="<mask>" , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , **__UpperCAmelCase , ) lowerCAmelCase__ :str = vocab_file lowerCAmelCase__ :Any = False if not self.vocab_file else True def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ :int = [self.cls_token_id] lowerCAmelCase__ :Optional[int] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.sep_token_id] lowerCAmelCase__ :Optional[int] = [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 , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(__UpperCAmelCase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return lowerCAmelCase__ :str = os.path.join( __UpperCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) return (out_vocab_file,)
293
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[Any] = """realm""" def __init__( self , __UpperCAmelCase=3_0_5_2_2 , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=1_2_8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=8 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu_new" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=5_1_2 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=2_5_6 , __UpperCAmelCase=1_0 , __UpperCAmelCase=1E-3 , __UpperCAmelCase=5 , __UpperCAmelCase=3_2_0 , __UpperCAmelCase=1_3_3_5_3_7_1_8 , __UpperCAmelCase=5_0_0_0 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=2 , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) # Common config lowerCAmelCase__ :List[str] = vocab_size lowerCAmelCase__ :Optional[Any] = max_position_embeddings lowerCAmelCase__ :Optional[Any] = hidden_size lowerCAmelCase__ :str = retriever_proj_size lowerCAmelCase__ :Any = num_hidden_layers lowerCAmelCase__ :Any = num_attention_heads lowerCAmelCase__ :List[str] = num_candidates lowerCAmelCase__ :Union[str, Any] = intermediate_size lowerCAmelCase__ :List[str] = hidden_act lowerCAmelCase__ :str = hidden_dropout_prob lowerCAmelCase__ :Tuple = attention_probs_dropout_prob lowerCAmelCase__ :Tuple = initializer_range lowerCAmelCase__ :Tuple = type_vocab_size lowerCAmelCase__ :Optional[int] = layer_norm_eps # Reader config lowerCAmelCase__ :Optional[Any] = span_hidden_size lowerCAmelCase__ :Dict = max_span_width lowerCAmelCase__ :Any = reader_layer_norm_eps lowerCAmelCase__ :Dict = reader_beam_size lowerCAmelCase__ :List[Any] = reader_seq_len # Retrieval config lowerCAmelCase__ :Optional[Any] = num_block_records lowerCAmelCase__ :Any = searcher_beam_size
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_plbart""": ["""PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PLBartConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""PLBartTokenizer"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """PLBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """PLBartForCausalLM""", """PLBartForConditionalGeneration""", """PLBartForSequenceClassification""", """PLBartModel""", """PLBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
293
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = KandinskyImgaImgPipeline __magic_name__ :List[Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] __magic_name__ :Optional[Any] = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] __magic_name__ :Any = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __magic_name__ :List[str] = False @property def snake_case ( self ): '''simple docstring''' return 3_2 @property def snake_case ( self ): '''simple docstring''' return 3_2 @property def snake_case ( self ): '''simple docstring''' return self.time_input_dim @property def snake_case ( self ): '''simple docstring''' return self.time_input_dim * 4 @property def snake_case ( self ): '''simple docstring''' return 1_0_0 @property def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base' ) return tokenizer @property def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Any = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) lowerCAmelCase__ :Tuple = MultilingualCLIP(__UpperCAmelCase ) lowerCAmelCase__ :Dict = text_encoder.eval() return text_encoder @property def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :str = { 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'text_image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'text_image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } lowerCAmelCase__ :int = UNetaDConditionModel(**__UpperCAmelCase ) return model @property def snake_case ( self ): '''simple docstring''' return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :int = VQModel(**self.dummy_movq_kwargs ) return model def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = self.dummy_text_encoder lowerCAmelCase__ :Any = self.dummy_tokenizer lowerCAmelCase__ :Optional[Any] = self.dummy_unet lowerCAmelCase__ :List[Any] = self.dummy_movq lowerCAmelCase__ :List[Any] = { 'num_train_timesteps': 1_0_0_0, 'beta_schedule': 'linear', 'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } lowerCAmelCase__ :List[str] = DDIMScheduler(**__UpperCAmelCase ) lowerCAmelCase__ :Any = { 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :List[str] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :str = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__UpperCAmelCase ) # create init_image lowerCAmelCase__ :str = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCAmelCase__ :Tuple = Image.fromarray(np.uinta(__UpperCAmelCase ) ).convert('RGB' ).resize((2_5_6, 2_5_6) ) if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Tuple = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :int = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'horse', 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 6_4, 'width': 6_4, 'num_inference_steps': 1_0, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'cpu' lowerCAmelCase__ :Dict = self.get_dummy_components() lowerCAmelCase__ :List[Any] = self.pipeline_class(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Dict = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) lowerCAmelCase__ :List[str] = output.images lowerCAmelCase__ :Any = pipe( **self.get_dummy_inputs(__UpperCAmelCase ) , return_dict=__UpperCAmelCase , )[0] lowerCAmelCase__ :List[Any] = image[0, -3:, -3:, -1] lowerCAmelCase__ :List[str] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowerCAmelCase__ :Union[str, Any] = np.array( [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/kandinsky_img2img_frog.npy' ) lowerCAmelCase__ :Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) lowerCAmelCase__ :str = 'A red cartoon frog, 4k' lowerCAmelCase__ :Any = KandinskyPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1-prior' , torch_dtype=torch.floataa ) pipe_prior.to(__UpperCAmelCase ) lowerCAmelCase__ :Dict = KandinskyImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1' , torch_dtype=torch.floataa ) lowerCAmelCase__ :Optional[int] = pipeline.to(__UpperCAmelCase ) pipeline.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = torch.Generator(device='cpu' ).manual_seed(0 ) lowerCAmelCase__ , lowerCAmelCase__ :Any = pipe_prior( __UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=5 , negative_prompt='' , ).to_tuple() lowerCAmelCase__ :Union[str, Any] = pipeline( __UpperCAmelCase , image=__UpperCAmelCase , image_embeds=__UpperCAmelCase , negative_image_embeds=__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type='np' , ) lowerCAmelCase__ :List[Any] = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
293
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
1
"""simple docstring""" import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging __A = logging.get_logger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( 'Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see' ' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation' ' instructions.' ) raise if not is_sharded: lowerCAmelCase__ :Optional[Any] = os.path.abspath(_SCREAMING_SNAKE_CASE ) logger.info(F"Loading PyTorch weights from {pt_path}" ) lowerCAmelCase__ :Union[str, Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) logger.info(F"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters." ) lowerCAmelCase__ :List[str] = convert_pytorch_state_dict_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files lowerCAmelCase__ :Optional[Any] = convert_pytorch_sharded_state_dict_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return flax_state_dict def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->(Tuple[str], np.ndarray): """simple docstring""" def is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ) -> bool: return len(set(_SCREAMING_SNAKE_CASE ) & {key, (model_prefix,) + key} ) > 0 # layer norm lowerCAmelCase__ :Dict = pt_tuple_key[:-1] + ('scale',) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean lowerCAmelCase__ :Dict = pt_tuple_key[:-1] + ('mean',) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var lowerCAmelCase__ :Optional[Any] = pt_tuple_key[:-1] + ('var',) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # embedding lowerCAmelCase__ :str = pt_tuple_key[:-1] + ('embedding',) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # conv layer lowerCAmelCase__ :Union[str, Any] = pt_tuple_key[:-1] + ('kernel',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer lowerCAmelCase__ :int = pt_tuple_key[:-1] + ('kernel',) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Any = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight lowerCAmelCase__ :str = pt_tuple_key[:-1] + ('weight',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias lowerCAmelCase__ :Optional[int] = pt_tuple_key[:-1] + ('bias',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 lowerCAmelCase__ :List[str] = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): lowerCAmelCase__ :Union[str, Any] = pt_tuple_key[-2] + '_g' elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): lowerCAmelCase__ :Any = pt_tuple_key[-2] + '_v' if name is not None: lowerCAmelCase__ :List[str] = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :str = {k: v.numpy() for k, v in pt_state_dict.items()} lowerCAmelCase__ :Tuple = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: lowerCAmelCase__ :Union[str, Any] = flax_model.params['params'] else: lowerCAmelCase__ :int = flax_model.params lowerCAmelCase__ :str = flatten_dict(_SCREAMING_SNAKE_CASE ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: lowerCAmelCase__ :List[str] = flatten_dict(flax_model.params['batch_stats'] ) random_flax_state_dict.update(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :int = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('.' )[0] for k in pt_state_dict.keys()} ) lowerCAmelCase__ :Dict = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('.' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): lowerCAmelCase__ :str = tuple(pt_key.split('.' ) ) # remove base model prefix if necessary lowerCAmelCase__ :Union[str, Any] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: lowerCAmelCase__ :Any = pt_tuple_key[1:] # Correctly rename weight parameters lowerCAmelCase__ , lowerCAmelCase__ :str = rename_key_and_reshape_tensor( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # add model prefix if necessary lowerCAmelCase__ :Dict = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: lowerCAmelCase__ :str = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " F"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: lowerCAmelCase__ :Union[str, Any] = jnp.asarray(_SCREAMING_SNAKE_CASE ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue # also add unexpected weight so that warning is thrown lowerCAmelCase__ :Optional[int] = jnp.asarray(_SCREAMING_SNAKE_CASE ) else: # also add unexpected weight so that warning is thrown lowerCAmelCase__ :Any = jnp.asarray(_SCREAMING_SNAKE_CASE ) return unflatten_dict(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[str]: """simple docstring""" import torch # Load the index lowerCAmelCase__ :Optional[Any] = {} for shard_file in shard_filenames: # load using msgpack utils lowerCAmelCase__ :List[str] = torch.load(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = {k: v.numpy() for k, v in pt_state_dict.items()} lowerCAmelCase__ :int = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: lowerCAmelCase__ :List[str] = flax_model.params['params'] lowerCAmelCase__ :str = flatten_dict(_SCREAMING_SNAKE_CASE ) random_flax_state_dict.update(flatten_dict(flax_model.params['batch_stats'] ) ) else: lowerCAmelCase__ :Any = flax_model.params lowerCAmelCase__ :Optional[int] = flatten_dict(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('.' )[0] for k in pt_state_dict.keys()} ) lowerCAmelCase__ :Dict = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('.' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): lowerCAmelCase__ :Tuple = tuple(pt_key.split('.' ) ) # remove base model prefix if necessary lowerCAmelCase__ :List[str] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: lowerCAmelCase__ :Optional[int] = pt_tuple_key[1:] # Correctly rename weight parameters lowerCAmelCase__ , lowerCAmelCase__ :Dict = rename_key_and_reshape_tensor( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # add model prefix if necessary lowerCAmelCase__ :Dict = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: lowerCAmelCase__ :List[str] = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " F"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: lowerCAmelCase__ :Any = jnp.asarray(_SCREAMING_SNAKE_CASE ) continue if "var" in flax_key[-1]: lowerCAmelCase__ :Tuple = jnp.asarray(_SCREAMING_SNAKE_CASE ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue # also add unexpected weight so that warning is thrown lowerCAmelCase__ :int = jnp.asarray(_SCREAMING_SNAKE_CASE ) else: # also add unexpected weight so that warning is thrown lowerCAmelCase__ :Optional[Any] = jnp.asarray(_SCREAMING_SNAKE_CASE ) return unflatten_dict(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = os.path.abspath(_SCREAMING_SNAKE_CASE ) logger.info(F"Loading Flax weights from {flax_checkpoint_path}" ) # import correct flax class lowerCAmelCase__ :List[Any] = getattr(_SCREAMING_SNAKE_CASE , 'Flax' + model.__class__.__name__ ) # load flax weight dict with open(_SCREAMING_SNAKE_CASE , 'rb' ) as state_f: try: lowerCAmelCase__ :str = from_bytes(_SCREAMING_SNAKE_CASE , state_f.read() ) except UnpicklingError: raise EnvironmentError(F"Unable to convert {flax_checkpoint_path} to Flax deserializable object. " ) return load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[str]: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( 'Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see' ' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation' ' instructions.' ) raise # check if we have bf16 weights lowerCAmelCase__ :str = flatten_dict(jax.tree_util.tree_map(lambda _SCREAMING_SNAKE_CASE : x.dtype == jnp.bfloataa , _SCREAMING_SNAKE_CASE ) ).values() if any(_SCREAMING_SNAKE_CASE ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( 'Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ' 'before loading those in PyTorch model.' ) lowerCAmelCase__ :Optional[int] = jax.tree_util.tree_map( lambda _SCREAMING_SNAKE_CASE : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = flatten_dict(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :int = pt_model.state_dict() lowerCAmelCase__ :Union[str, Any] = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split('.' )[0] for k in pt_model_dict.keys()} ) lowerCAmelCase__ :List[str] = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split('.' )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys lowerCAmelCase__ :Any = [] lowerCAmelCase__ :Union[str, Any] = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): lowerCAmelCase__ :Tuple = flax_key_tuple[0] == pt_model.base_model_prefix lowerCAmelCase__ :Tuple = '.'.join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: lowerCAmelCase__ :Tuple = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: lowerCAmelCase__ :Union[str, Any] = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(_SCREAMING_SNAKE_CASE ) not in pt_model_dict: # conv layer lowerCAmelCase__ :List[Any] = flax_key_tuple[:-1] + ('weight',) lowerCAmelCase__ :int = jnp.transpose(_SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(_SCREAMING_SNAKE_CASE ) not in pt_model_dict: # linear layer lowerCAmelCase__ :List[str] = flax_key_tuple[:-1] + ('weight',) lowerCAmelCase__ :int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: lowerCAmelCase__ :int = flax_key_tuple[:-1] + ('weight',) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: lowerCAmelCase__ :Any = flax_key_tuple[:-1] + ('running_mean',) elif "var" in flax_key_tuple[-1]: lowerCAmelCase__ :str = flax_key_tuple[:-1] + ('running_var',) if "batch_stats" in flax_state: lowerCAmelCase__ :Optional[int] = '.'.join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: lowerCAmelCase__ :Tuple = '.'.join(_SCREAMING_SNAKE_CASE ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. lowerCAmelCase__ :Tuple = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: lowerCAmelCase__ :List[str] = key.split('.' ) lowerCAmelCase__ :Tuple = None if key_components[-3::2] == ["parametrizations", "original0"]: lowerCAmelCase__ :str = key_components[-2] + '_g' elif key_components[-3::2] == ["parametrizations", "original1"]: lowerCAmelCase__ :List[str] = key_components[-2] + '_v' if name is not None: lowerCAmelCase__ :Optional[int] = key_components[:-3] + [name] lowerCAmelCase__ :Optional[Any] = '.'.join(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = key if flax_key in special_pt_names: lowerCAmelCase__ :Optional[int] = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " F"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." ) else: # add weight to pytorch dict lowerCAmelCase__ :List[Any] = np.asarray(_SCREAMING_SNAKE_CASE ) if not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) else flax_tensor lowerCAmelCase__ :str = torch.from_numpy(_SCREAMING_SNAKE_CASE ) # remove from missing keys missing_keys.remove(_SCREAMING_SNAKE_CASE ) else: # weight is not expected by PyTorch model unexpected_keys.append(_SCREAMING_SNAKE_CASE ) pt_model.load_state_dict(_SCREAMING_SNAKE_CASE ) # re-transform missing_keys to list lowerCAmelCase__ :Optional[int] = list(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: logger.warning( 'Some weights of the Flax model were not used when initializing the PyTorch model' F" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" F" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" ' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This' F" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" ' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a' ' FlaxBertForSequenceClassification model).' ) else: logger.warning(F"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n" ) if len(_SCREAMING_SNAKE_CASE ) > 0: logger.warning( F"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" F" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" ' use it for predictions and inference.' ) else: logger.warning( F"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n" 'If your task is similar to the task the model of the checkpoint was trained on, ' F"you can already use {pt_model.__class__.__name__} for predictions without further training." ) return pt_model
293
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" from __future__ import annotations import numpy as np def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" return np.maximum(0 , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
293
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
1
"""simple docstring""" import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version __A = version.parse(importlib_metadata.version("""nltk""")) if NLTK_VERSION >= version.Version("""3.6.4"""): from nltk import word_tokenize __A = """\ @inproceedings{banarjee2005, title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments}, author = {Banerjee, Satanjeev and Lavie, Alon}, booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization}, month = jun, year = {2005}, address = {Ann Arbor, Michigan}, publisher = {Association for Computational Linguistics}, url = {https://www.aclweb.org/anthology/W05-0909}, pages = {65--72}, } """ __A = """\ METEOR, an automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations. Unigrams can be matched based on their surface forms, stemmed forms, and meanings; furthermore, METEOR can be easily extended to include more advanced matching strategies. Once all generalized unigram matches between the two strings have been found, METEOR computes a score for this matching using a combination of unigram-precision, unigram-recall, and a measure of fragmentation that is designed to directly capture how well-ordered the matched words in the machine translation are in relation to the reference. METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic data and 0.331 on the Chinese data. This is shown to be an improvement on using simply unigram-precision, unigram-recall and their harmonic F1 combination. """ __A = """ Computes METEOR score of translated segments against one or more references. Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. alpha: Parameter for controlling relative weights of precision and recall. default: 0.9 beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3 gamma: Relative weight assigned to fragmentation penalty. default: 0.5 Returns: 'meteor': meteor score. Examples: >>> meteor = datasets.load_metric('meteor') >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"] >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"] >>> results = meteor.compute(predictions=predictions, references=references) >>> print(round(results[\"meteor\"], 4)) 0.6944 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): """simple docstring""" def snake_case ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=0.9 , __UpperCAmelCase=3 , __UpperCAmelCase=0.5 ): '''simple docstring''' if NLTK_VERSION >= version.Version('3.6.5' ): lowerCAmelCase__ :List[str] = [ meteor_score.single_meteor_score( word_tokenize(__UpperCAmelCase ) , word_tokenize(__UpperCAmelCase ) , alpha=__UpperCAmelCase , beta=__UpperCAmelCase , gamma=__UpperCAmelCase ) for ref, pred in zip(__UpperCAmelCase , __UpperCAmelCase ) ] else: lowerCAmelCase__ :Tuple = [ meteor_score.single_meteor_score(__UpperCAmelCase , __UpperCAmelCase , alpha=__UpperCAmelCase , beta=__UpperCAmelCase , gamma=__UpperCAmelCase ) for ref, pred in zip(__UpperCAmelCase , __UpperCAmelCase ) ] return {"meteor": np.mean(__UpperCAmelCase )}
293
"""simple docstring""" 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 _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = 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(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
1
"""simple docstring""" from string import ascii_lowercase, ascii_uppercase def __A (_SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" if not sentence: return "" lowerCAmelCase__ :str = dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" from __future__ import annotations def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" print(F"Vertex\tShortest Distance from vertex {src}" ) for i, d in enumerate(_SCREAMING_SNAKE_CASE ): print(F"{i}\t\t{d}" ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Any: """simple docstring""" for j in range(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = (graph[j][k] for k in ['src', 'dst', 'weight']) if distance[u] != float('inf' ) and distance[u] + w < distance[v]: return True return False def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->list[float]: """simple docstring""" lowerCAmelCase__ :str = [float('inf' )] * vertex_count lowerCAmelCase__ :Union[str, Any] = 0.0 for _ in range(vertex_count - 1 ): for j in range(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = (graph[j][k] for k in ['src', 'dst', 'weight']) if distance[u] != float('inf' ) and distance[u] + w < distance[v]: lowerCAmelCase__ :str = distance[u] + w lowerCAmelCase__ :int = check_negative_cycle(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if negative_cycle_exists: raise Exception('Negative cycle found' ) return distance if __name__ == "__main__": import doctest doctest.testmod() __A = int(input("""Enter number of vertices: """).strip()) __A = int(input("""Enter number of edges: """).strip()) __A = [{} for _ in range(E)] for i in range(E): print("""Edge """, i + 1) __A , __A , __A = ( int(x) for x in input("""Enter source, destination, weight: """).strip().split(""" """) ) __A = {"""src""": src, """dst""": dest, """weight""": weight} __A = int(input("""\nEnter shortest path source:""").strip()) __A = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
293
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
1
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __A = logging.get_logger(__name__) # TODO: upload to AWS __A = { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json""" ), } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Tuple = """retribert""" def __init__( self , __UpperCAmelCase=3_0_5_2_2 , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=5_1_2 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=True , __UpperCAmelCase=1_2_8 , __UpperCAmelCase=0 , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase__ :Any = vocab_size lowerCAmelCase__ :Union[str, Any] = hidden_size lowerCAmelCase__ :Tuple = num_hidden_layers lowerCAmelCase__ :Tuple = num_attention_heads lowerCAmelCase__ :Union[str, Any] = hidden_act lowerCAmelCase__ :Optional[int] = intermediate_size lowerCAmelCase__ :Optional[int] = hidden_dropout_prob lowerCAmelCase__ :Union[str, Any] = attention_probs_dropout_prob lowerCAmelCase__ :Dict = max_position_embeddings lowerCAmelCase__ :List[str] = type_vocab_size lowerCAmelCase__ :List[Any] = initializer_range lowerCAmelCase__ :Union[str, Any] = layer_norm_eps lowerCAmelCase__ :List[Any] = share_encoders lowerCAmelCase__ :Optional[int] = projection_dim
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __A = """\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, title = {BLEU: a Method for Automatic Evaluation of Machine Translation}, booktitle = {}, year = {2002}, pages = {311--318} } @inproceedings{lin-och-2004-orange, title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\", author = \"Lin, Chin-Yew and Och, Franz Josef\", booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\", month = \"aug 23{--}aug 27\", year = \"2004\", address = \"Geneva, Switzerland\", publisher = \"COLING\", url = \"https://www.aclweb.org/anthology/C04-1072\", pages = \"501--507\", } """ __A = """\ BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another. Quality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation, the better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and remains one of the most popular automated and inexpensive metrics. Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations. Those scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness are not taken into account[citation needed]. BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. """ __A = """ Computes BLEU score of translated segments against one or more references. Args: predictions: list of translations to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: 'bleu': bleu score, 'precisions': geometric mean of n-gram precisions, 'brevity_penalty': brevity penalty, 'length_ratio': ratio of lengths, 'translation_length': translation_length, 'reference_length': reference_length Examples: >>> predictions = [ ... [\"hello\", \"there\", \"general\", \"kenobi\"], # tokenized prediction of the first sample ... [\"foo\", \"bar\", \"foobar\"] # tokenized prediction of the second sample ... ] >>> references = [ ... [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]], # tokenized references for the first sample (2 references) ... [[\"foo\", \"bar\", \"foobar\"]] # tokenized references for the second sample (1 reference) ... ] >>> bleu = datasets.load_metric(\"bleu\") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results[\"bleu\"]) 1.0 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): """simple docstring""" def snake_case ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ) , id='references' ), } ) , codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'] , reference_urls=[ 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=4 , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :List[Any] = compute_bleu( reference_corpus=__UpperCAmelCase , translation_corpus=__UpperCAmelCase , max_order=__UpperCAmelCase , smooth=__UpperCAmelCase ) ((lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__)) :Optional[int] = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
293
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """sayakpaul/vit-msn-base""": """https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json""", # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = """vit_msn""" def __init__( self , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-06 , __UpperCAmelCase=2_2_4 , __UpperCAmelCase=1_6 , __UpperCAmelCase=3 , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) lowerCAmelCase__ :Any = hidden_size lowerCAmelCase__ :Tuple = num_hidden_layers lowerCAmelCase__ :str = num_attention_heads lowerCAmelCase__ :Optional[Any] = intermediate_size lowerCAmelCase__ :Dict = hidden_act lowerCAmelCase__ :str = hidden_dropout_prob lowerCAmelCase__ :str = attention_probs_dropout_prob lowerCAmelCase__ :Optional[int] = initializer_range lowerCAmelCase__ :Dict = layer_norm_eps lowerCAmelCase__ :List[Any] = image_size lowerCAmelCase__ :Tuple = patch_size lowerCAmelCase__ :Any = num_channels lowerCAmelCase__ :str = qkv_bias
293
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""} class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Tuple = """ctrl""" __magic_name__ :List[Any] = ["""past_key_values"""] __magic_name__ :Tuple = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , __UpperCAmelCase=2_4_6_5_3_4 , __UpperCAmelCase=2_5_6 , __UpperCAmelCase=1_2_8_0 , __UpperCAmelCase=8_1_9_2 , __UpperCAmelCase=4_8 , __UpperCAmelCase=1_6 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=1E-6 , __UpperCAmelCase=0.02 , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :int = vocab_size lowerCAmelCase__ :List[Any] = n_positions lowerCAmelCase__ :Tuple = n_embd lowerCAmelCase__ :Any = n_layer lowerCAmelCase__ :str = n_head lowerCAmelCase__ :Optional[Any] = dff lowerCAmelCase__ :List[Any] = resid_pdrop lowerCAmelCase__ :Dict = embd_pdrop lowerCAmelCase__ :Dict = layer_norm_epsilon lowerCAmelCase__ :Tuple = initializer_range lowerCAmelCase__ :List[str] = use_cache super().__init__(**__UpperCAmelCase )
293
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __A = [ """EAGER""", """AOT_EAGER""", """INDUCTOR""", """NVFUSER""", """AOT_NVFUSER""", """AOT_CUDAGRAPHS""", """OFI""", """FX2TRT""", """ONNXRT""", """IPEX""", ] def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) ->int: """simple docstring""" lowerCAmelCase__ :int = True while ask_again: lowerCAmelCase__ :Optional[Any] = input(_SCREAMING_SNAKE_CASE ) try: if default is not None and len(_SCREAMING_SNAKE_CASE ) == 0: return default return convert_value(_SCREAMING_SNAKE_CASE ) if convert_value is not None else result except Exception: if error_message is not None: print(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=[] , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0 ) ->Any: """simple docstring""" lowerCAmelCase__ :List[str] = BulletMenu(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = menu.run(default_choice=_SCREAMING_SNAKE_CASE ) return convert_value(_SCREAMING_SNAKE_CASE ) if convert_value is not None else result def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :int = int(_SCREAMING_SNAKE_CASE ) return ComputeEnvironment(['LOCAL_MACHINE', 'AMAZON_SAGEMAKER'][value] ) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = int(_SCREAMING_SNAKE_CASE ) return DistributedType(['NO', 'MULTI_CPU', 'MULTI_XPU', 'MULTI_GPU', 'MULTI_NPU', 'TPU'][value] ) def __A (_SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" lowerCAmelCase__ :List[Any] = int(_SCREAMING_SNAKE_CASE ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = int(_SCREAMING_SNAKE_CASE ) return PrecisionType(['no', 'fp16', 'bf16', 'fp8'][value] ) def __A (_SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = int(_SCREAMING_SNAKE_CASE ) return SageMakerDistributedType(['NO', 'DATA_PARALLEL', 'MODEL_PARALLEL'][value] ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" return {"yes": True, "no": False}[value.lower()] class _lowerCAmelCase ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = super()._format_usage(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Dict = usage.replace('<command> [<args>] ' , '' ) return usage
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup __A = """https://www.indeed.co.in/jobs?q=mobile+app+development&l=""" def __A (_SCREAMING_SNAKE_CASE = "mumbai" ) ->Generator[tuple[str, str], None, None]: """simple docstring""" lowerCAmelCase__ :Dict = BeautifulSoup(requests.get(url + location ).content , 'html.parser' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('div' , attrs={'data-tn-component': 'organicJob'} ): lowerCAmelCase__ :Any = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip() lowerCAmelCase__ :List[str] = job.find('span' , {'class': 'company'} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("""Bangalore"""), 1): print(F'''Job {i:>2} is {job[0]} at {job[1]}''')
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" import numpy as np def __A (_SCREAMING_SNAKE_CASE ) ->np.array: """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
293
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( 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 _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" 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 = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = 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' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'laion/clap-htsat-unfused' lowerCAmelCase__ :str = tempfile.mkdtemp() def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_tokenizer() lowerCAmelCase__ :Tuple = self.get_feature_extractor() lowerCAmelCase__ :Optional[Any] = ClapProcessor(tokenizer=__UpperCAmelCase , feature_extractor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :Any = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCAmelCase__ :List[Any] = self.get_feature_extractor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) lowerCAmelCase__ :str = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = self.get_feature_extractor() lowerCAmelCase__ :List[str] = self.get_tokenizer() lowerCAmelCase__ :List[str] = ClapProcessor(tokenizer=__UpperCAmelCase , feature_extractor=__UpperCAmelCase ) lowerCAmelCase__ :str = floats_list((3, 1_0_0_0) ) lowerCAmelCase__ :Optional[Any] = feature_extractor(__UpperCAmelCase , return_tensors='np' ) lowerCAmelCase__ :Optional[int] = processor(audios=__UpperCAmelCase , 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 ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self.get_feature_extractor() lowerCAmelCase__ :Dict = self.get_tokenizer() lowerCAmelCase__ :Dict = ClapProcessor(tokenizer=__UpperCAmelCase , feature_extractor=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = 'This is a test string' lowerCAmelCase__ :Optional[int] = processor(text=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = self.get_feature_extractor() lowerCAmelCase__ :Dict = self.get_tokenizer() lowerCAmelCase__ :Optional[int] = ClapProcessor(tokenizer=__UpperCAmelCase , feature_extractor=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCAmelCase__ :List[Any] = processor.batch_decode(__UpperCAmelCase ) lowerCAmelCase__ :int = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.get_feature_extractor() lowerCAmelCase__ :List[str] = self.get_tokenizer() lowerCAmelCase__ :Union[str, Any] = ClapProcessor(tokenizer=__UpperCAmelCase , feature_extractor=__UpperCAmelCase ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
293
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
1
"""simple docstring""" import os import sys import unittest __A = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __A = os.path.join(git_repo_path, """src""", """diffusers""") class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = find_backend(' if not is_torch_available():' ) self.assertEqual(__UpperCAmelCase , 'torch' ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") lowerCAmelCase__ :int = find_backend(' if not (is_torch_available() and is_transformers_available()):' ) self.assertEqual(__UpperCAmelCase , 'torch_and_transformers' ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") lowerCAmelCase__ :Union[str, Any] = find_backend( ' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):' ) self.assertEqual(__UpperCAmelCase , 'torch_and_transformers_and_onnx' ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch' , __UpperCAmelCase ) self.assertIn('torch_and_transformers' , __UpperCAmelCase ) self.assertIn('flax_and_transformers' , __UpperCAmelCase ) self.assertIn('torch_and_transformers_and_onnx' , __UpperCAmelCase ) # Likewise, we can't assert on the exact content of a key self.assertIn('UNet2DModel' , objects['torch'] ) self.assertIn('FlaxUNet2DConditionModel' , objects['flax'] ) self.assertIn('StableDiffusionPipeline' , objects['torch_and_transformers'] ) self.assertIn('FlaxStableDiffusionPipeline' , objects['flax_and_transformers'] ) self.assertIn('LMSDiscreteScheduler' , objects['torch_and_scipy'] ) self.assertIn('OnnxStableDiffusionPipeline' , objects['torch_and_transformers_and_onnx'] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = create_dummy_object('CONSTANT' , '\'torch\'' ) self.assertEqual(__UpperCAmelCase , '\nCONSTANT = None\n' ) lowerCAmelCase__ :List[str] = create_dummy_object('function' , '\'torch\'' ) self.assertEqual( __UpperCAmelCase , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' ) lowerCAmelCase__ :Any = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n' lowerCAmelCase__ :Optional[int] = create_dummy_object('FakeClass' , '\'torch\'' ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n' lowerCAmelCase__ :int = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} ) self.assertEqual(dummy_files['torch'] , __UpperCAmelCase )
293
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
1
"""simple docstring""" from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "x" , _SCREAMING_SNAKE_CASE = 10**-10 , _SCREAMING_SNAKE_CASE = 1 , ) ->complex: """simple docstring""" lowerCAmelCase__ :Tuple = symbols(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = lambdify(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = lambdify(_SCREAMING_SNAKE_CASE , diff(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ :Dict = starting_point while True: if diff_function(_SCREAMING_SNAKE_CASE ) != 0: lowerCAmelCase__ :Optional[Any] = prev_guess - multiplicity * func(_SCREAMING_SNAKE_CASE ) / diff_function( _SCREAMING_SNAKE_CASE ) else: raise ZeroDivisionError('Could not find root' ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess lowerCAmelCase__ :List[Any] = next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F'''The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}''') # Find root of polynomial # Find fourth Root of 5 print(F'''The root of x**4 - 5 = 0 is {newton_raphson("x**4 -5", 0.4 +5J)}''') # Find value of e print( """The root of log(y) - 1 = 0 is """, F'''{newton_raphson("log(y) - 1", 2, variable="y")}''', ) # Exponential Roots print( """The root of exp(x) - 1 = 0 is""", F'''{newton_raphson("exp(x) - 1", 10, precision=0.005)}''', ) # Find root of cos(x) print(F'''The root of cos(x) = 0 is {newton_raphson("cos(x)", 0)}''')
293
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], '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]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
1
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { """configuration_pegasus_x""": ["""PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PegasusXConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST""", """PegasusXForConditionalGeneration""", """PegasusXModel""", """PegasusXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
1
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( 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 _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" 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 = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = 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' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
1
"""simple docstring""" # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES __A = """tiny-wmt19-en-ru""" # Build # borrowed from a test __A = [ """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>""", ] __A = dict(zip(vocab, range(len(vocab)))) __A = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: __A = Path(tmpdirname) __A = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] __A = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] __A = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) __A = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) __A = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1000, tgt_vocab_size=1000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) __A = FSMTForConditionalGeneration(config) print(F'''num of params {tiny_model.num_parameters()}''') # Test __A = tokenizer(["""Making tiny model"""], return_tensors="""pt""") __A = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F'''Generated {mname_tiny}''') # Upload # transformers-cli upload tiny-wmt19-en-ru
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :int = DistilBertTokenizer __magic_name__ :Tuple = DistilBertTokenizerFast __magic_name__ :Dict = True @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = DistilBertTokenizer.from_pretrained('distilbert-base-uncased' ) lowerCAmelCase__ :Union[str, Any] = tokenizer.encode('sequence builders' , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
293
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""", # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[Any] = """sew-d""" def __init__( self , __UpperCAmelCase=3_2 , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase=2 , __UpperCAmelCase=5_1_2 , __UpperCAmelCase=2_5_6 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=("p2c", "c2p") , __UpperCAmelCase="layer_norm" , __UpperCAmelCase="gelu_python" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-7 , __UpperCAmelCase=1E-5 , __UpperCAmelCase="group" , __UpperCAmelCase="gelu" , __UpperCAmelCase=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , __UpperCAmelCase=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , __UpperCAmelCase=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , __UpperCAmelCase=False , __UpperCAmelCase=1_2_8 , __UpperCAmelCase=1_6 , __UpperCAmelCase=True , __UpperCAmelCase=0.05 , __UpperCAmelCase=1_0 , __UpperCAmelCase=2 , __UpperCAmelCase=0.0 , __UpperCAmelCase=1_0 , __UpperCAmelCase=0 , __UpperCAmelCase="mean" , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=2_5_6 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , __UpperCAmelCase=2 , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__UpperCAmelCase , pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase ) lowerCAmelCase__ :int = hidden_size lowerCAmelCase__ :Dict = feat_extract_norm lowerCAmelCase__ :Tuple = feat_extract_activation lowerCAmelCase__ :List[str] = list(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = list(__UpperCAmelCase ) lowerCAmelCase__ :int = list(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = conv_bias lowerCAmelCase__ :List[Any] = num_conv_pos_embeddings lowerCAmelCase__ :List[Any] = num_conv_pos_embedding_groups lowerCAmelCase__ :Union[str, Any] = len(self.conv_dim ) lowerCAmelCase__ :Union[str, Any] = num_hidden_layers lowerCAmelCase__ :Optional[Any] = intermediate_size lowerCAmelCase__ :int = squeeze_factor lowerCAmelCase__ :Any = max_position_embeddings lowerCAmelCase__ :List[str] = position_buckets lowerCAmelCase__ :Optional[Any] = share_att_key lowerCAmelCase__ :Optional[int] = relative_attention lowerCAmelCase__ :List[Any] = norm_rel_ebd lowerCAmelCase__ :Tuple = list(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = hidden_act lowerCAmelCase__ :Optional[int] = num_attention_heads lowerCAmelCase__ :Dict = hidden_dropout lowerCAmelCase__ :List[Any] = attention_dropout lowerCAmelCase__ :str = activation_dropout lowerCAmelCase__ :Any = feat_proj_dropout lowerCAmelCase__ :str = final_dropout lowerCAmelCase__ :Optional[Any] = layer_norm_eps lowerCAmelCase__ :str = feature_layer_norm_eps lowerCAmelCase__ :Tuple = initializer_range lowerCAmelCase__ :Optional[int] = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' F"but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)" F"= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowerCAmelCase__ :List[str] = apply_spec_augment lowerCAmelCase__ :List[str] = mask_time_prob lowerCAmelCase__ :Dict = mask_time_length lowerCAmelCase__ :str = mask_time_min_masks lowerCAmelCase__ :Optional[Any] = mask_feature_prob lowerCAmelCase__ :str = mask_feature_length lowerCAmelCase__ :Union[str, Any] = mask_feature_min_masks # ctc loss lowerCAmelCase__ :List[str] = ctc_loss_reduction lowerCAmelCase__ :Optional[int] = ctc_zero_infinity # sequence classification lowerCAmelCase__ :Union[str, Any] = use_weighted_layer_sum lowerCAmelCase__ :Tuple = classifier_proj_size @property def snake_case ( self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
293
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
1
"""simple docstring""" import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def __A (_SCREAMING_SNAKE_CASE = 3 ) ->qiskit.result.counts.Counts: """simple docstring""" if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(_SCREAMING_SNAKE_CASE ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) lowerCAmelCase__ :List[Any] = QuantumRegister(_SCREAMING_SNAKE_CASE , 'qr' ) lowerCAmelCase__ :Any = ClassicalRegister(_SCREAMING_SNAKE_CASE , 'cr' ) lowerCAmelCase__ :List[str] = QuantumCircuit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = number_of_qubits for i in range(_SCREAMING_SNAKE_CASE ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(_SCREAMING_SNAKE_CASE ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(_SCREAMING_SNAKE_CASE , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # simulate with 10000 shots lowerCAmelCase__ :Any = Aer.get_backend('qasm_simulator' ) lowerCAmelCase__ :Any = execute(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , shots=1_0000 ) return job.result().get_counts(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print( F'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
293
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="""%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s""", datefmt="""%Y-%m-%d %H:%M:%S""", level=os.environ.get("""LOGLEVEL""", """INFO""").upper(), stream=sys.stdout, ) __A = logging.getLogger(__name__) __A = {"""facebook/bart-base""": BartForConditionalGeneration} __A = {"""facebook/bart-base""": BartTokenizer} def __A () ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser(description='Export Bart model + Beam Search to ONNX graph.' ) parser.add_argument( '--validation_file' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='A csv or a json file containing the validation data.' ) parser.add_argument( '--max_length' , type=_SCREAMING_SNAKE_CASE , default=5 , help='The maximum total input sequence length after tokenization.' , ) parser.add_argument( '--num_beams' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help=( 'Number of beams to use for evaluation. This argument will be ' 'passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.' ) , ) parser.add_argument( '--model_name_or_path' , type=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_SCREAMING_SNAKE_CASE , ) parser.add_argument( '--config_name' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name' , ) parser.add_argument( '--device' , type=_SCREAMING_SNAKE_CASE , default='cpu' , help='Device where the model will be run' , ) parser.add_argument('--output_file_path' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='Where to store the final ONNX file.' ) lowerCAmelCase__ :Optional[int] = parser.parse_args() return args def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="cpu" ) ->str: """simple docstring""" lowerCAmelCase__ :Optional[Any] = model_dict[model_name].from_pretrained(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = tokenizer_dict[model_name].from_pretrained(_SCREAMING_SNAKE_CASE ) if model_name in ["facebook/bart-base"]: lowerCAmelCase__ :List[str] = 0 lowerCAmelCase__ :Optional[int] = None lowerCAmelCase__ :Optional[int] = 0 return huggingface_model, tokenizer def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[str]: """simple docstring""" model.eval() lowerCAmelCase__ :str = None lowerCAmelCase__ :List[Any] = torch.jit.script(BARTBeamSearchGenerator(_SCREAMING_SNAKE_CASE ) ) with torch.no_grad(): lowerCAmelCase__ :Dict = 'My friends are cool but they eat too many carbs.' lowerCAmelCase__ :Tuple = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors='pt' ).to(model.device ) lowerCAmelCase__ :Union[str, Any] = model.generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , num_beams=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , early_stopping=_SCREAMING_SNAKE_CASE , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( _SCREAMING_SNAKE_CASE , ( inputs['input_ids'], inputs['attention_mask'], num_beams, max_length, model.config.decoder_start_token_id, ) , _SCREAMING_SNAKE_CASE , opset_version=14 , input_names=['input_ids', 'attention_mask', 'num_beams', 'max_length', 'decoder_start_token_id'] , output_names=['output_ids'] , dynamic_axes={ 'input_ids': {0: 'batch', 1: 'seq'}, 'output_ids': {0: 'batch', 1: 'seq_out'}, } , example_outputs=_SCREAMING_SNAKE_CASE , ) logger.info('Model exported to {}'.format(_SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ :Tuple = remove_dup_initializers(os.path.abspath(_SCREAMING_SNAKE_CASE ) ) logger.info('Deduplicated and optimized model written to {}'.format(_SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ :Union[str, Any] = onnxruntime.InferenceSession(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = ort_sess.run( _SCREAMING_SNAKE_CASE , { 'input_ids': inputs['input_ids'].cpu().numpy(), 'attention_mask': inputs['attention_mask'].cpu().numpy(), 'num_beams': np.array(_SCREAMING_SNAKE_CASE ), 'max_length': np.array(_SCREAMING_SNAKE_CASE ), 'decoder_start_token_id': np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3 ) logger.info('Model outputs from torch and ONNX Runtime are similar.' ) logger.info('Success.' ) def __A () ->Dict: """simple docstring""" lowerCAmelCase__ :List[Any] = parse_args() lowerCAmelCase__ :int = 5 lowerCAmelCase__ :List[str] = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() lowerCAmelCase__ :Tuple = torch.device(args.device ) lowerCAmelCase__ , lowerCAmelCase__ :str = load_model_tokenizer(args.model_name_or_path , _SCREAMING_SNAKE_CASE ) if model.config.decoder_start_token_id is None: raise ValueError('Make sure that `config.decoder_start_token_id` is correctly defined' ) model.to(_SCREAMING_SNAKE_CASE ) if args.max_length: lowerCAmelCase__ :Union[str, Any] = args.max_length if args.num_beams: lowerCAmelCase__ :List[str] = args.num_beams if args.output_file_path: lowerCAmelCase__ :Tuple = args.output_file_path else: lowerCAmelCase__ :Optional[Any] = 'BART.onnx' logger.info('Exporting model to ONNX' ) export_and_validate_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
1
"""simple docstring""" from sklearn.metrics import recall_score import datasets __A = """ Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is the false negatives. """ __A = """ Args: - **predictions** (`list` of `int`): The predicted labels. - **references** (`list` of `int`): The ground truth labels. - **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. - **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`. - **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). - **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. - **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised. - `0`: If there is a zero division, the return value is `0`. - `1`: If there is a zero division, the return value is `1`. Returns: - **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. Examples: Example 1-A simple example with some errors >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) >>> print(results) {'recall': 0.6666666666666666} Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) >>> print(results) {'recall': 0.5} Example 3-The same example as Example 1, but with `sample_weight` included. >>> recall_metric = datasets.load_metric('recall') >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) >>> print(results) {'recall': 0.55} Example 4-A multiclass example, using different averages. >>> recall_metric = datasets.load_metric('recall') >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'recall': array([1., 0., 0.])} """ __A = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): """simple docstring""" def snake_case ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html'] , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase="binary" , __UpperCAmelCase=None , __UpperCAmelCase="warn" , ): '''simple docstring''' lowerCAmelCase__ :List[Any] = recall_score( __UpperCAmelCase , __UpperCAmelCase , labels=__UpperCAmelCase , pos_label=__UpperCAmelCase , average=__UpperCAmelCase , sample_weight=__UpperCAmelCase , zero_division=__UpperCAmelCase , ) return {"recall": float(__UpperCAmelCase ) if score.size == 1 else score}
293
"""simple docstring""" 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 _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = 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(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""], """tokenization_perceiver""": ["""PerceiverTokenizer"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""PerceiverFeatureExtractor"""] __A = ["""PerceiverImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PerceiverForImageClassificationConvProcessing""", """PerceiverForImageClassificationFourier""", """PerceiverForImageClassificationLearned""", """PerceiverForMaskedLM""", """PerceiverForMultimodalAutoencoding""", """PerceiverForOpticalFlow""", """PerceiverForSequenceClassification""", """PerceiverLayer""", """PerceiverModel""", """PerceiverPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
293
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" import argparse from collections import defaultdict import yaml __A = """docs/source/en/_toctree.yml""" def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = defaultdict(_SCREAMING_SNAKE_CASE ) for doc in model_doc: counts[doc["local"]] += 1 lowerCAmelCase__ :Optional[Any] = [key for key, value in counts.items() if value > 1] lowerCAmelCase__ :Optional[Any] = [] for duplicate_key in duplicates: lowerCAmelCase__ :Tuple = list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key} ) if len(_SCREAMING_SNAKE_CASE ) > 1: raise ValueError( F"{duplicate_key} is present several times in the documentation table of content at " '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ' 'others.' ) # Only add this once new_doc.append({'local': duplicate_key, 'title': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1] ) # Sort return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : s["title"].lower() ) def __A (_SCREAMING_SNAKE_CASE=False ) ->Dict: """simple docstring""" with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: lowerCAmelCase__ :Optional[int] = yaml.safe_load(f.read() ) # Get to the API doc lowerCAmelCase__ :Optional[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowerCAmelCase__ :Optional[Any] = content[api_idx]['sections'] # Then to the model doc lowerCAmelCase__ :Union[str, Any] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 lowerCAmelCase__ :Dict = api_doc[model_idx]['sections'] lowerCAmelCase__ :Dict = [(idx, section) for idx, section in enumerate(_SCREAMING_SNAKE_CASE ) if 'sections' in section] lowerCAmelCase__ :Optional[Any] = False for idx, modality_doc in modalities_docs: lowerCAmelCase__ :Optional[Any] = modality_doc['sections'] lowerCAmelCase__ :Optional[int] = clean_model_doc_toc(_SCREAMING_SNAKE_CASE ) if old_modality_doc != new_modality_doc: lowerCAmelCase__ :Optional[Any] = True if overwrite: lowerCAmelCase__ :str = new_modality_doc if diff: if overwrite: lowerCAmelCase__ :Optional[int] = model_doc lowerCAmelCase__ :Optional[int] = api_doc with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(_SCREAMING_SNAKE_CASE , allow_unicode=_SCREAMING_SNAKE_CASE ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") __A = parser.parse_args() check_model_doc(args.fix_and_overwrite)
293
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """microsoft/swinv2-tiny-patch4-window8-256""": ( """https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json""" ), } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Tuple = """swinv2""" __magic_name__ :List[str] = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , __UpperCAmelCase=2_2_4 , __UpperCAmelCase=4 , __UpperCAmelCase=3 , __UpperCAmelCase=9_6 , __UpperCAmelCase=[2, 2, 6, 2] , __UpperCAmelCase=[3, 6, 1_2, 2_4] , __UpperCAmelCase=7 , __UpperCAmelCase=4.0 , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase="gelu" , __UpperCAmelCase=False , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=3_2 , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) lowerCAmelCase__ :Dict = image_size lowerCAmelCase__ :Optional[Any] = patch_size lowerCAmelCase__ :Tuple = num_channels lowerCAmelCase__ :int = embed_dim lowerCAmelCase__ :str = depths lowerCAmelCase__ :List[Any] = len(__UpperCAmelCase ) lowerCAmelCase__ :str = num_heads lowerCAmelCase__ :Union[str, Any] = window_size lowerCAmelCase__ :List[str] = mlp_ratio lowerCAmelCase__ :List[Any] = qkv_bias lowerCAmelCase__ :Dict = hidden_dropout_prob lowerCAmelCase__ :List[Any] = attention_probs_dropout_prob lowerCAmelCase__ :str = drop_path_rate lowerCAmelCase__ :Union[str, Any] = hidden_act lowerCAmelCase__ :List[Any] = use_absolute_embeddings lowerCAmelCase__ :str = layer_norm_eps lowerCAmelCase__ :List[str] = initializer_range lowerCAmelCase__ :Union[str, Any] = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowerCAmelCase__ :Dict = int(embed_dim * 2 ** (len(__UpperCAmelCase ) - 1) ) lowerCAmelCase__ :List[Any] = (0, 0, 0, 0)
293
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
1
"""simple docstring""" __A = """0.21.0""" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
293
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { """configuration_bloom""": ["""BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BloomConfig""", """BloomOnnxConfig"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""BloomTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST""", """BloomForCausalLM""", """BloomModel""", """BloomPreTrainedModel""", """BloomForSequenceClassification""", """BloomForTokenClassification""", """BloomForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( 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 _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" 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 = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = 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' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
1
"""simple docstring""" from __future__ import annotations def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->list[str]: """simple docstring""" if partitions <= 0: raise ValueError('partitions must be a positive number!' ) if partitions > number_of_bytes: raise ValueError('partitions can not > number_of_bytes!' ) lowerCAmelCase__ :Any = number_of_bytes // partitions lowerCAmelCase__ :Dict = [] for i in range(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = i * bytes_per_partition + 1 lowerCAmelCase__ :Dict = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(F"{start_bytes}-{end_bytes}" ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
293
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
1
"""simple docstring""" import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( 'stabilityai/stable-diffusion-2' , revision='bf16' , dtype=jnp.bfloataa , ) lowerCAmelCase__ :Dict = 'A painting of a squirrel eating a burger' lowerCAmelCase__ :List[Any] = jax.device_count() lowerCAmelCase__ :Dict = num_samples * [prompt] lowerCAmelCase__ :Tuple = sd_pipe.prepare_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = replicate(__UpperCAmelCase ) lowerCAmelCase__ :Dict = shard(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = jax.random.PRNGKey(0 ) lowerCAmelCase__ :Optional[Any] = jax.random.split(__UpperCAmelCase , jax.device_count() ) lowerCAmelCase__ :List[Any] = sd_pipe(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , num_inference_steps=2_5 , jit=__UpperCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3) lowerCAmelCase__ :str = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) lowerCAmelCase__ :Any = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] lowerCAmelCase__ :Tuple = jnp.asarray(jax.device_get(image_slice.flatten() ) ) lowerCAmelCase__ :Any = jnp.array([0.42_38, 0.44_14, 0.43_95, 0.44_53, 0.46_29, 0.45_90, 0.45_31, 0.4_55_08, 0.45_12] ) print(F"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 'stabilityai/stable-diffusion-2' lowerCAmelCase__ , lowerCAmelCase__ :int = FlaxDPMSolverMultistepScheduler.from_pretrained(__UpperCAmelCase , subfolder='scheduler' ) lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = FlaxStableDiffusionPipeline.from_pretrained( __UpperCAmelCase , scheduler=__UpperCAmelCase , revision='bf16' , dtype=jnp.bfloataa , ) lowerCAmelCase__ :Union[str, Any] = scheduler_params lowerCAmelCase__ :Dict = 'A painting of a squirrel eating a burger' lowerCAmelCase__ :Optional[Any] = jax.device_count() lowerCAmelCase__ :Dict = num_samples * [prompt] lowerCAmelCase__ :Dict = sd_pipe.prepare_inputs(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = replicate(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = shard(__UpperCAmelCase ) lowerCAmelCase__ :Dict = jax.random.PRNGKey(0 ) lowerCAmelCase__ :Optional[int] = jax.random.split(__UpperCAmelCase , jax.device_count() ) lowerCAmelCase__ :str = sd_pipe(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , num_inference_steps=2_5 , jit=__UpperCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3) lowerCAmelCase__ :Union[str, Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) lowerCAmelCase__ :Dict = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] lowerCAmelCase__ :List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) lowerCAmelCase__ :Optional[int] = jnp.array([0.43_36, 0.4_29_69, 0.44_53, 0.41_99, 0.42_97, 0.45_31, 0.44_34, 0.44_34, 0.42_97] ) print(F"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
293
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
1
"""simple docstring""" import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer lowerCAmelCase__ :Dict = flax_key_tuple[:-1] + ('weight',) lowerCAmelCase__ :Optional[Any] = torch.permute(_SCREAMING_SNAKE_CASE , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(_SCREAMING_SNAKE_CASE ): # linear layer lowerCAmelCase__ :Any = flax_key_tuple[:-1] + ('weight',) lowerCAmelCase__ :int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: lowerCAmelCase__ :int = flax_key_tuple[:-1] + ('weight',) return flax_key_tuple, flax_tensor def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Any: """simple docstring""" if "metadata" in layer: lowerCAmelCase__ :Optional[Any] = layer.split('metadata' ) lowerCAmelCase__ :Tuple = ''.join(split_layer[0] )[:-1] lowerCAmelCase__ :Optional[int] = [tuple(('metadata' + split_layer[1]).split('/' ) )] elif "kvstore" in layer: lowerCAmelCase__ :List[Any] = layer.split('kvstore' ) lowerCAmelCase__ :Union[str, Any] = ''.join(split_layer[0] )[:-1] lowerCAmelCase__ :Any = [tuple(('kvstore' + split_layer[1]).split('/' ) )] else: lowerCAmelCase__ :Optional[Any] = layer.split('/' ) lowerCAmelCase__ :Tuple = '/'.join(split_layer[:-1] ) lowerCAmelCase__ :int = (split_layer[-1],) if "kvstore/path" in layer: lowerCAmelCase__ :str = F"{switch_checkpoint_path}/{checkpoint_info[layer]}" elif "kvstore/driver" in layer: lowerCAmelCase__ :List[Any] = 'file' else: lowerCAmelCase__ :Optional[Any] = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :Optional[int] = rename_keys(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = {} for k, v in current_block.items(): lowerCAmelCase__ :Union[str, Any] = v lowerCAmelCase__ :Optional[Any] = new_current_block torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = WEIGHTS_NAME ) ->int: """simple docstring""" lowerCAmelCase__ :Optional[Any] = convert_file_size_to_int(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Optional[Any] = 0 lowerCAmelCase__ :int = 0 os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) with gfile.GFile(switch_checkpoint_path + '/checkpoint' , 'rb' ) as fp: lowerCAmelCase__ :Optional[int] = serialization.msgpack_restore(fp.read() )['optimizer']['target'] lowerCAmelCase__ :Tuple = flatten_dict(_SCREAMING_SNAKE_CASE , sep='/' ) lowerCAmelCase__ :List[str] = {} for layer in checkpoint_info.keys(): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = get_key_and_tensorstore_dict( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if curr_real_layer_name in all_layers: lowerCAmelCase__ :Dict = content else: lowerCAmelCase__ :Tuple = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file lowerCAmelCase__ :Dict = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() lowerCAmelCase__ :Optional[int] = torch.tensor(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts lowerCAmelCase__ , lowerCAmelCase__ :List[str] = rename_base_flax_keys(tuple(key.split('/' ) ) , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = '/'.join(_SCREAMING_SNAKE_CASE ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: lowerCAmelCase__ :Optional[int] = os.path.join( _SCREAMING_SNAKE_CASE , weights_name.replace('.bin' , F"-{len(_SCREAMING_SNAKE_CASE )+1:05d}-of-???.bin" ) ) rename_and_save_block(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) sharded_state_dicts.append(current_block.keys() ) del current_block lowerCAmelCase__ :Dict = {} lowerCAmelCase__ :List[Any] = 0 lowerCAmelCase__ :Optional[Any] = raw_weights.to(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) current_block_size += weight_size total_size += weight_size # Add the last block lowerCAmelCase__ :Optional[Any] = os.path.join(_SCREAMING_SNAKE_CASE , weights_name.replace('.bin' , F"-{len(_SCREAMING_SNAKE_CASE )+1:05d}-of-???.bin" ) ) rename_and_save_block(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(_SCREAMING_SNAKE_CASE ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index lowerCAmelCase__ :Union[str, Any] = {} lowerCAmelCase__ :Optional[Any] = {} for idx, shard in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[str] = weights_name.replace( '.bin' , F"-{idx+1:05d}-of-{len(_SCREAMING_SNAKE_CASE ):05d}.bin" ) # len(sharded_state_dicts):05d} lowerCAmelCase__ :Tuple = os.path.join(_SCREAMING_SNAKE_CASE , weights_name.replace('.bin' , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ :Dict = shard for key in shard: lowerCAmelCase__ :Optional[Any] = shard_file # Add the metadata lowerCAmelCase__ :Optional[int] = {'total_size': total_size} lowerCAmelCase__ :Any = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 'w' , encoding='utf-8' ) as f: lowerCAmelCase__ :Optional[int] = json.dumps(_SCREAMING_SNAKE_CASE , indent=2 , sort_keys=_SCREAMING_SNAKE_CASE ) + '\n' f.write(_SCREAMING_SNAKE_CASE ) return metadata, index if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600""", type=str, required=False, help="""Path to a directory containing a folder per layer. Follows the original Google format.""", ) parser.add_argument("""--max_shard_size""", default="""10GB""", required=False, help="""Max shard size""") parser.add_argument("""--dtype""", default="""bfloat16""", type=str, required=False, help="""dtype of the saved model""") parser.add_argument( """--pytorch_dump_folder_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted""", type=str, required=False, help="""Path to the output pytorch model.""", ) __A = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __A () ->List[str]: """simple docstring""" from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer lowerCAmelCase__ :Optional[Any] = SwitchTransformersConfig.from_pretrained('google/switch-base-8' ) config.save_pretrained('/home/arthur_huggingface_co/transformers/switch_converted' ) lowerCAmelCase__ :Optional[Any] = SwitchTransformersForConditionalGeneration.from_pretrained( '/home/arthur_huggingface_co/transformers/switch_converted' , device_map='auto' ) lowerCAmelCase__ :List[str] = TaTokenizer.from_pretrained('t5-small' ) lowerCAmelCase__ :List[str] = 'A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.' lowerCAmelCase__ :Any = tokenizer(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).input_ids lowerCAmelCase__ :str = model.generate(_SCREAMING_SNAKE_CASE , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
293
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], '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]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
1
"""simple docstring""" def __A () ->Dict: """simple docstring""" lowerCAmelCase__ :str = 0 for i in range(1 , 1001 ): total += i**i return str(_SCREAMING_SNAKE_CASE )[-10:] if __name__ == "__main__": print(solution())
293
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :"DiagonalGaussianDistribution" class _lowerCAmelCase ( a , a ): """simple docstring""" __magic_name__ :Union[str, Any] = True @register_to_config def __init__( self , __UpperCAmelCase = 3 , __UpperCAmelCase = 3 , __UpperCAmelCase = ("DownEncoderBlock2D",) , __UpperCAmelCase = ("UpDecoderBlock2D",) , __UpperCAmelCase = (6_4,) , __UpperCAmelCase = 1 , __UpperCAmelCase = "silu" , __UpperCAmelCase = 4 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 0.1_82_15 , ): '''simple docstring''' super().__init__() # pass init params to Encoder lowerCAmelCase__ :Optional[Any] = Encoder( in_channels=__UpperCAmelCase , out_channels=__UpperCAmelCase , down_block_types=__UpperCAmelCase , block_out_channels=__UpperCAmelCase , layers_per_block=__UpperCAmelCase , act_fn=__UpperCAmelCase , norm_num_groups=__UpperCAmelCase , double_z=__UpperCAmelCase , ) # pass init params to Decoder lowerCAmelCase__ :Any = Decoder( in_channels=__UpperCAmelCase , out_channels=__UpperCAmelCase , up_block_types=__UpperCAmelCase , block_out_channels=__UpperCAmelCase , layers_per_block=__UpperCAmelCase , norm_num_groups=__UpperCAmelCase , act_fn=__UpperCAmelCase , ) lowerCAmelCase__ :Dict = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) lowerCAmelCase__ :List[str] = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , 1 ) lowerCAmelCase__ :List[str] = False lowerCAmelCase__ :Any = False # only relevant if vae tiling is enabled lowerCAmelCase__ :Tuple = self.config.sample_size lowerCAmelCase__ :Optional[Any] = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) lowerCAmelCase__ :Tuple = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) lowerCAmelCase__ :List[Any] = 0.25 def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' if isinstance(__UpperCAmelCase , (Encoder, Decoder) ): lowerCAmelCase__ :Tuple = value def snake_case ( self , __UpperCAmelCase = True ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = use_tiling def snake_case ( self ): '''simple docstring''' self.enable_tiling(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = True def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = {} def fn_recursive_add_processors(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): if hasattr(__UpperCAmelCase , 'set_processor' ): lowerCAmelCase__ :str = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" , __UpperCAmelCase , __UpperCAmelCase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) return processors def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = len(self.attn_processors.keys() ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(__UpperCAmelCase )} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): if hasattr(__UpperCAmelCase , 'set_processor' ): if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): module.set_processor(__UpperCAmelCase ) else: module.set_processor(processor.pop(F"{name}.processor" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" , __UpperCAmelCase , __UpperCAmelCase ) for name, module in self.named_children(): fn_recursive_attn_processor(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = True ): '''simple docstring''' if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(__UpperCAmelCase , return_dict=__UpperCAmelCase ) if self.use_slicing and x.shape[0] > 1: lowerCAmelCase__ :Tuple = [self.encoder(__UpperCAmelCase ) for x_slice in x.split(1 )] lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = self.encoder(__UpperCAmelCase ) lowerCAmelCase__ :Dict = self.quant_conv(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = DiagonalGaussianDistribution(__UpperCAmelCase ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = True ): '''simple docstring''' if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(__UpperCAmelCase , return_dict=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = self.post_quant_conv(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self.decoder(__UpperCAmelCase ) if not return_dict: return (dec,) return DecoderOutput(sample=__UpperCAmelCase ) @apply_forward_hook def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = True ): '''simple docstring''' if self.use_slicing and z.shape[0] > 1: lowerCAmelCase__ :str = [self._decode(__UpperCAmelCase ).sample for z_slice in z.split(1 )] lowerCAmelCase__ :str = torch.cat(__UpperCAmelCase ) else: lowerCAmelCase__ :int = self._decode(__UpperCAmelCase ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = min(a.shape[2] , b.shape[2] , __UpperCAmelCase ) for y in range(__UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = min(a.shape[3] , b.shape[3] , __UpperCAmelCase ) for x in range(__UpperCAmelCase ): lowerCAmelCase__ :Tuple = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = True ): '''simple docstring''' lowerCAmelCase__ :List[Any] = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) lowerCAmelCase__ :Optional[Any] = int(self.tile_latent_min_size * self.tile_overlap_factor ) lowerCAmelCase__ :Any = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. lowerCAmelCase__ :Optional[int] = [] for i in range(0 , x.shape[2] , __UpperCAmelCase ): lowerCAmelCase__ :Dict = [] for j in range(0 , x.shape[3] , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] lowerCAmelCase__ :int = self.encoder(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = self.quant_conv(__UpperCAmelCase ) row.append(__UpperCAmelCase ) rows.append(__UpperCAmelCase ) lowerCAmelCase__ :int = [] for i, row in enumerate(__UpperCAmelCase ): lowerCAmelCase__ :Tuple = [] for j, tile in enumerate(__UpperCAmelCase ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: lowerCAmelCase__ :Tuple = self.blend_v(rows[i - 1][j] , __UpperCAmelCase , __UpperCAmelCase ) if j > 0: lowerCAmelCase__ :Union[str, Any] = self.blend_h(row[j - 1] , __UpperCAmelCase , __UpperCAmelCase ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(__UpperCAmelCase , dim=3 ) ) lowerCAmelCase__ :List[Any] = torch.cat(__UpperCAmelCase , dim=2 ) lowerCAmelCase__ :int = DiagonalGaussianDistribution(__UpperCAmelCase ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = True ): '''simple docstring''' lowerCAmelCase__ :Dict = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) lowerCAmelCase__ :List[str] = int(self.tile_sample_min_size * self.tile_overlap_factor ) lowerCAmelCase__ :List[str] = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. lowerCAmelCase__ :Any = [] for i in range(0 , z.shape[2] , __UpperCAmelCase ): lowerCAmelCase__ :int = [] for j in range(0 , z.shape[3] , __UpperCAmelCase ): lowerCAmelCase__ :Any = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] lowerCAmelCase__ :Dict = self.post_quant_conv(__UpperCAmelCase ) lowerCAmelCase__ :Dict = self.decoder(__UpperCAmelCase ) row.append(__UpperCAmelCase ) rows.append(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = [] for i, row in enumerate(__UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = [] for j, tile in enumerate(__UpperCAmelCase ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: lowerCAmelCase__ :str = self.blend_v(rows[i - 1][j] , __UpperCAmelCase , __UpperCAmelCase ) if j > 0: lowerCAmelCase__ :Union[str, Any] = self.blend_h(row[j - 1] , __UpperCAmelCase , __UpperCAmelCase ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(__UpperCAmelCase , dim=3 ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = False , __UpperCAmelCase = True , __UpperCAmelCase = None , ): '''simple docstring''' lowerCAmelCase__ :Tuple = sample lowerCAmelCase__ :List[str] = self.encode(__UpperCAmelCase ).latent_dist if sample_posterior: lowerCAmelCase__ :Tuple = posterior.sample(generator=__UpperCAmelCase ) else: lowerCAmelCase__ :List[Any] = posterior.mode() lowerCAmelCase__ :List[Any] = self.decode(__UpperCAmelCase ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__UpperCAmelCase )
293
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
1
"""simple docstring""" import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed __A = { """distilbert""": (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), """roberta""": (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), """bert""": (BertConfig, BertForMaskedLM, BertTokenizer), """gpt2""": (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" if args.student_type == "roberta": lowerCAmelCase__ :str = False elif args.student_type == "gpt2": lowerCAmelCase__ :List[Any] = False def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" if args.student_type == "roberta": lowerCAmelCase__ :List[str] = False def __A () ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = argparse.ArgumentParser(description='Training' ) parser.add_argument('--force' , action='store_true' , help='Overwrite dump_path if it already exists.' ) parser.add_argument( '--dump_path' , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory (log, checkpoints, parameters, etc.)' ) parser.add_argument( '--data_file' , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The binarized file (tokenized + tokens_to_ids) and grouped by sequence.' , ) parser.add_argument( '--student_type' , type=_SCREAMING_SNAKE_CASE , choices=['distilbert', 'roberta', 'gpt2'] , required=_SCREAMING_SNAKE_CASE , help='The student type (DistilBERT, RoBERTa).' , ) parser.add_argument('--student_config' , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to the student configuration.' ) parser.add_argument( '--student_pretrained_weights' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Load student initialization checkpoint.' ) parser.add_argument( '--teacher_type' , choices=['bert', 'roberta', 'gpt2'] , required=_SCREAMING_SNAKE_CASE , help='Teacher type (BERT, RoBERTa).' ) parser.add_argument('--teacher_name' , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The teacher model.' ) parser.add_argument('--temperature' , default=2.0 , type=_SCREAMING_SNAKE_CASE , help='Temperature for the softmax temperature.' ) parser.add_argument( '--alpha_ce' , default=0.5 , type=_SCREAMING_SNAKE_CASE , help='Linear weight for the distillation loss. Must be >=0.' ) parser.add_argument( '--alpha_mlm' , default=0.0 , type=_SCREAMING_SNAKE_CASE , help='Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.' , ) parser.add_argument('--alpha_clm' , default=0.5 , type=_SCREAMING_SNAKE_CASE , help='Linear weight for the CLM loss. Must be >=0.' ) parser.add_argument('--alpha_mse' , default=0.0 , type=_SCREAMING_SNAKE_CASE , help='Linear weight of the MSE loss. Must be >=0.' ) parser.add_argument( '--alpha_cos' , default=0.0 , type=_SCREAMING_SNAKE_CASE , help='Linear weight of the cosine embedding loss. Must be >=0.' ) parser.add_argument( '--mlm' , action='store_true' , help='The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.' ) parser.add_argument( '--mlm_mask_prop' , default=0.1_5 , type=_SCREAMING_SNAKE_CASE , help='Proportion of tokens for which we need to make a prediction.' , ) parser.add_argument('--word_mask' , default=0.8 , type=_SCREAMING_SNAKE_CASE , help='Proportion of tokens to mask out.' ) parser.add_argument('--word_keep' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Proportion of tokens to keep.' ) parser.add_argument('--word_rand' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Proportion of tokens to randomly replace.' ) parser.add_argument( '--mlm_smoothing' , default=0.7 , type=_SCREAMING_SNAKE_CASE , help='Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).' , ) parser.add_argument('--token_counts' , type=_SCREAMING_SNAKE_CASE , help='The token counts in the data_file for MLM.' ) parser.add_argument( '--restrict_ce_to_mask' , action='store_true' , help='If true, compute the distillation loss only the [MLM] prediction distribution.' , ) parser.add_argument( '--freeze_pos_embs' , action='store_true' , help='Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.' , ) parser.add_argument( '--freeze_token_type_embds' , action='store_true' , help='Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.' , ) parser.add_argument('--n_epoch' , type=_SCREAMING_SNAKE_CASE , default=3 , help='Number of pass on the whole dataset.' ) parser.add_argument('--batch_size' , type=_SCREAMING_SNAKE_CASE , default=5 , help='Batch size (for each process).' ) parser.add_argument( '--group_by_size' , action='store_false' , help='If true, group sequences that have similar length into the same batch. Default is true.' , ) parser.add_argument( '--gradient_accumulation_steps' , type=_SCREAMING_SNAKE_CASE , default=50 , help='Gradient accumulation for larger training batches.' , ) parser.add_argument('--warmup_prop' , default=0.0_5 , type=_SCREAMING_SNAKE_CASE , help='Linear warmup proportion.' ) parser.add_argument('--weight_decay' , default=0.0 , type=_SCREAMING_SNAKE_CASE , help='Weight decay if we apply some.' ) parser.add_argument('--learning_rate' , default=5e-4 , type=_SCREAMING_SNAKE_CASE , help='The initial learning rate for Adam.' ) parser.add_argument('--adam_epsilon' , default=1e-6 , type=_SCREAMING_SNAKE_CASE , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , default=5.0 , type=_SCREAMING_SNAKE_CASE , help='Max gradient norm.' ) parser.add_argument('--initializer_range' , default=0.0_2 , type=_SCREAMING_SNAKE_CASE , help='Random initialization range.' ) parser.add_argument( '--fp16' , action='store_true' , help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' , ) parser.add_argument( '--fp16_opt_level' , type=_SCREAMING_SNAKE_CASE , default='O1' , help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) , ) parser.add_argument('--n_gpu' , type=_SCREAMING_SNAKE_CASE , default=1 , help='Number of GPUs in the node.' ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='Distributed training - Local rank' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=56 , help='Random seed' ) parser.add_argument('--log_interval' , type=_SCREAMING_SNAKE_CASE , default=500 , help='Tensorboard logging interval.' ) parser.add_argument('--checkpoint_interval' , type=_SCREAMING_SNAKE_CASE , default=4000 , help='Checkpoint interval.' ) lowerCAmelCase__ :List[str] = parser.parse_args() sanity_checks(_SCREAMING_SNAKE_CASE ) # ARGS # init_gpu_params(_SCREAMING_SNAKE_CASE ) set_seed(_SCREAMING_SNAKE_CASE ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( F"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" ' itUse `--force` if you want to overwrite it' ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(F"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(F"Param: {args}" ) with open(os.path.join(args.dump_path , 'parameters.json' ) , 'w' ) as f: json.dump(vars(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE , indent=4 ) git_log(args.dump_path ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = MODEL_CLASSES[args.student_type] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = MODEL_CLASSES[args.teacher_type] # TOKENIZER # lowerCAmelCase__ :Optional[Any] = teacher_tokenizer_class.from_pretrained(args.teacher_name ) lowerCAmelCase__ :List[str] = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): lowerCAmelCase__ :Optional[Any] = tokenizer.all_special_tokens.index(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = tokenizer.all_special_ids[idx] logger.info(F"Special tokens {special_tok_ids}" ) lowerCAmelCase__ :Union[str, Any] = special_tok_ids lowerCAmelCase__ :str = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(F"Loading data from {args.data_file}" ) with open(args.data_file , 'rb' ) as fp: lowerCAmelCase__ :Optional[Any] = pickle.load(_SCREAMING_SNAKE_CASE ) if args.mlm: logger.info(F"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , 'rb' ) as fp: lowerCAmelCase__ :Optional[int] = pickle.load(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = np.maximum(_SCREAMING_SNAKE_CASE , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): lowerCAmelCase__ :Optional[int] = 0.0 # do not predict special tokens lowerCAmelCase__ :Any = torch.from_numpy(_SCREAMING_SNAKE_CASE ) else: lowerCAmelCase__ :Dict = None lowerCAmelCase__ :Optional[int] = LmSeqsDataset(params=_SCREAMING_SNAKE_CASE , data=_SCREAMING_SNAKE_CASE ) logger.info('Data loader created.' ) # STUDENT # logger.info(F"Loading student config from {args.student_config}" ) lowerCAmelCase__ :List[Any] = student_config_class.from_pretrained(args.student_config ) lowerCAmelCase__ :Optional[Any] = True if args.student_pretrained_weights is not None: logger.info(F"Loading pretrained weights from {args.student_pretrained_weights}" ) lowerCAmelCase__ :int = student_model_class.from_pretrained(args.student_pretrained_weights , config=_SCREAMING_SNAKE_CASE ) else: lowerCAmelCase__ :Union[str, Any] = student_model_class(_SCREAMING_SNAKE_CASE ) if args.n_gpu > 0: student.to(F"cuda:{args.local_rank}" ) logger.info('Student loaded.' ) # TEACHER # lowerCAmelCase__ :Dict = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=_SCREAMING_SNAKE_CASE ) if args.n_gpu > 0: teacher.to(F"cuda:{args.local_rank}" ) logger.info(F"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if args.freeze_token_type_embds: freeze_token_type_embeddings(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() lowerCAmelCase__ :Dict = Distiller( params=_SCREAMING_SNAKE_CASE , dataset=_SCREAMING_SNAKE_CASE , token_probs=_SCREAMING_SNAKE_CASE , student=_SCREAMING_SNAKE_CASE , teacher=_SCREAMING_SNAKE_CASE ) distiller.train() logger.info('Let\'s go get some drinks.' ) if __name__ == "__main__": main()
293
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) __A = logging.getLogger() def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :Optional[Any] = {} lowerCAmelCase__ :Optional[Any] = os.path.join(_SCREAMING_SNAKE_CASE , 'all_results.json' ) if os.path.exists(_SCREAMING_SNAKE_CASE ): with open(_SCREAMING_SNAKE_CASE , 'r' ) as f: lowerCAmelCase__ :Dict = json.load(_SCREAMING_SNAKE_CASE ) else: raise ValueError(F"can't find {path}" ) return results __A = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self ): '''simple docstring''' import xla_spawn lowerCAmelCase__ :Dict = self.get_auto_remove_tmp_dir() lowerCAmelCase__ :Tuple = F"\n ./examples/pytorch/text-classification/run_glue.py\n --num_cores=8\n ./examples/pytorch/text-classification/run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --do_train\n --do_eval\n --debug tpu_metrics_debug\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --max_steps=10\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n ".split() with patch.object(__UpperCAmelCase , 'argv' , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = time() xla_spawn.main() lowerCAmelCase__ :int = time() lowerCAmelCase__ :List[str] = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['eval_accuracy'] , 0.75 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 5_0_0 ) def snake_case ( self ): '''simple docstring''' import xla_spawn lowerCAmelCase__ :List[Any] = '\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n '.split() with patch.object(__UpperCAmelCase , 'argv' , __UpperCAmelCase ): xla_spawn.main()
293
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
1
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE = 10 , _SCREAMING_SNAKE_CASE = 22 ) ->int: """simple docstring""" lowerCAmelCase__ :Any = range(1 , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = range(1 , _SCREAMING_SNAKE_CASE ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F'''{solution(10, 22) = }''')
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) ->List[Any]: """simple docstring""" if attention_mask is None: lowerCAmelCase__ :Tuple = tf.cast(tf.math.not_equal(_SCREAMING_SNAKE_CASE , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class _lowerCAmelCase : """simple docstring""" __magic_name__ :Tuple = OPTConfig __magic_name__ :Tuple = {} __magic_name__ :Union[str, Any] = """gelu""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=1_3 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=9_9 , __UpperCAmelCase=1_6 , __UpperCAmelCase=2 , __UpperCAmelCase=4 , __UpperCAmelCase=4 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=2_0 , __UpperCAmelCase=2 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=1_6 , __UpperCAmelCase=1_6 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = parent lowerCAmelCase__ :Optional[int] = batch_size lowerCAmelCase__ :Tuple = seq_length lowerCAmelCase__ :Any = is_training lowerCAmelCase__ :List[str] = use_labels lowerCAmelCase__ :Optional[int] = vocab_size lowerCAmelCase__ :str = hidden_size lowerCAmelCase__ :int = num_hidden_layers lowerCAmelCase__ :int = num_attention_heads lowerCAmelCase__ :Optional[Any] = intermediate_size lowerCAmelCase__ :Optional[Any] = hidden_act lowerCAmelCase__ :Optional[int] = hidden_dropout_prob lowerCAmelCase__ :Union[str, Any] = attention_probs_dropout_prob lowerCAmelCase__ :List[str] = max_position_embeddings lowerCAmelCase__ :Optional[int] = eos_token_id lowerCAmelCase__ :Any = pad_token_id lowerCAmelCase__ :List[str] = bos_token_id lowerCAmelCase__ :Any = embed_dim lowerCAmelCase__ :List[Any] = word_embed_proj_dim lowerCAmelCase__ :str = False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCAmelCase__ :int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCAmelCase__ :List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCAmelCase__ :Dict = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=__UpperCAmelCase , **self.config_updates , ) lowerCAmelCase__ :Dict = prepare_opt_inputs_dict(__UpperCAmelCase , __UpperCAmelCase ) return config, inputs_dict def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = TFOPTModel(config=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = inputs_dict['input_ids'] lowerCAmelCase__ :List[Any] = input_ids[:1, :] lowerCAmelCase__ :Tuple = inputs_dict['attention_mask'][:1, :] lowerCAmelCase__ :Optional[Any] = 1 # first forward pass lowerCAmelCase__ :List[str] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ :Tuple = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCAmelCase__ :Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase__ :List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowerCAmelCase__ :Tuple = tf.concat([input_ids, next_tokens] , axis=-1 ) lowerCAmelCase__ :Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowerCAmelCase__ :str = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase )[0] lowerCAmelCase__ :List[str] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowerCAmelCase__ :int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowerCAmelCase__ :List[Any] = output_from_no_past[:, -3:, random_slice_idx] lowerCAmelCase__ :str = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-3 ) @require_tf class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[Any] = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () __magic_name__ :List[Any] = (TFOPTForCausalLM,) if is_tf_available() else () __magic_name__ :Dict = ( {"""feature-extraction""": TFOPTModel, """text-generation""": TFOPTForCausalLM} if is_tf_available() else {} ) __magic_name__ :List[str] = False __magic_name__ :Optional[int] = False __magic_name__ :Optional[Any] = False __magic_name__ :Union[str, Any] = 10 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = TFOPTModelTester(self ) lowerCAmelCase__ :Tuple = ConfigTester(self , config_class=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.config_tester.run_common_tests() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(__UpperCAmelCase , __UpperCAmelCase ): if hasattr(__UpperCAmelCase , 'weight' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(__UpperCAmelCase , 'weight' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 1_0, config.vocab_size + 1_0]: # build the embeddings lowerCAmelCase__ :Optional[Any] = model_class(config=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = _get_word_embedding_weight(__UpperCAmelCase , model.get_input_embeddings() ) lowerCAmelCase__ :List[Any] = _get_word_embedding_weight(__UpperCAmelCase , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = _get_word_embedding_weight(__UpperCAmelCase , model.get_input_embeddings() ) lowerCAmelCase__ :Any = _get_word_embedding_weight(__UpperCAmelCase , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. lowerCAmelCase__ :Union[str, Any] = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , __UpperCAmelCase ) # check that weights remain the same after resizing lowerCAmelCase__ :int = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowerCAmelCase__ :str = False self.assertTrue(__UpperCAmelCase ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowerCAmelCase__ :List[Any] = False self.assertTrue(__UpperCAmelCase ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" return tf.constant(_SCREAMING_SNAKE_CASE , dtype=tf.intaa ) @require_tf class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = 99 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = tf.ones((4, 1) , dtype=tf.intaa ) * 2 lowerCAmelCase__ :Optional[Any] = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) lowerCAmelCase__ :int = input_ids.shape[0] lowerCAmelCase__ :Optional[Any] = OPTConfig( vocab_size=self.vocab_size , hidden_size=2_4 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = TFOPTModel.from_pretrained('facebook/opt-350m' ) lowerCAmelCase__ :Dict = _long_tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) lowerCAmelCase__ :int = tf.not_equal(__UpperCAmelCase , model.config.pad_token_id ) with tf.GradientTape(): lowerCAmelCase__ :int = model(input_ids=__UpperCAmelCase , attention_mask=__UpperCAmelCase ).last_hidden_state lowerCAmelCase__ :Dict = (1, 1_1, 5_1_2) self.assertEqual(output.shape , __UpperCAmelCase ) lowerCAmelCase__ :Dict = tf.constant( [[-0.28_73, -1.92_18, -0.30_33], [-1.27_10, -0.13_38, -0.19_02], [0.40_95, 0.12_14, -1.31_21]] ) self.assertTrue(np.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=4E-3 ) ) lowerCAmelCase__ :List[Any] = tf.function(__UpperCAmelCase , jit_compile=__UpperCAmelCase ) lowerCAmelCase__ :int = xla_generate(__UpperCAmelCase , __UpperCAmelCase )[0] self.assertTrue(np.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=4E-2 ) ) @require_tf @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().setUp() lowerCAmelCase__ :List[str] = 'facebook/opt-350m' def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = TFOPTForCausalLM.from_pretrained(self.path_model ) lowerCAmelCase__ :List[Any] = GPTaTokenizer.from_pretrained(self.path_model ) lowerCAmelCase__ :int = [ 'Today is a beautiful day and I want to', 'In the city of', 'Paris is the capital of France and', 'Computers and mobile phones have taken', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False lowerCAmelCase__ :List[str] = tokenizer(__UpperCAmelCase , return_tensors='tf' , padding=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) lowerCAmelCase__ :Tuple = tf.constant( [ [1.38_51, -13.89_23, -10.52_29, -10.75_33, -0.23_09, -10.23_84, -0.53_65, -9.09_47, -5.16_70], [-4.70_73, -10.62_76, -3.94_15, -21.52_42, -0.28_22, -0.28_22, -0.28_22, -0.28_22, -0.28_22], [0.62_47, -3.42_29, -8.91_79, -1.42_97, -14.16_50, 1.41_46, -9.02_18, -0.27_03, -0.27_03], [6.47_83, -1.99_13, -10.79_26, -2.33_36, 1.50_92, -0.99_74, -6.82_13, 1.34_77, 1.34_77], ] ) self.assertTrue(np.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4 ) ) lowerCAmelCase__ :List[Any] = tf.function(__UpperCAmelCase , jit_compile=__UpperCAmelCase ) lowerCAmelCase__ :Dict = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4 ) ) @require_tf @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @property def snake_case ( self ): '''simple docstring''' return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'facebook/opt-125m' lowerCAmelCase__ :List[str] = [ 'Today is a beautiful day and I want to', 'In the city of New York, the city', 'Paris is the capital of France and the capital', 'Computers and mobile phones have taken over the', ] lowerCAmelCase__ :Any = [] lowerCAmelCase__ :int = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) for prompt in self.prompts: lowerCAmelCase__ :List[Any] = tokenizer(__UpperCAmelCase , return_tensors='tf' ).input_ids lowerCAmelCase__ :List[Any] = model.generate(__UpperCAmelCase , max_length=1_0 ) lowerCAmelCase__ :Dict = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) predicted_outputs += generated_string self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'facebook/opt-350m' lowerCAmelCase__ :List[Any] = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = 'left' # use different length sentences to test batching lowerCAmelCase__ :Any = [ 'Hello, my dog is a little', 'Today, I', ] lowerCAmelCase__ :Dict = tokenizer(__UpperCAmelCase , return_tensors='tf' , padding=__UpperCAmelCase ) lowerCAmelCase__ :str = inputs['input_ids'] lowerCAmelCase__ :Optional[int] = model.generate(input_ids=__UpperCAmelCase , attention_mask=inputs['attention_mask'] ) lowerCAmelCase__ :str = tokenizer(sentences[0] , return_tensors='tf' ).input_ids lowerCAmelCase__ :List[str] = model.generate(input_ids=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['attention_mask'][-1] , tf.intaa ) ) lowerCAmelCase__ :Dict = tokenizer(sentences[1] , return_tensors='tf' ).input_ids lowerCAmelCase__ :List[str] = model.generate(input_ids=__UpperCAmelCase , max_length=model.config.max_length - num_paddings ) lowerCAmelCase__ :List[Any] = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :int = [ 'Hello, my dog is a little bit of a dork.\nI\'m a little bit', 'Today, I was in the middle of a conversation with a friend about the', ] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , [non_padded_sentence, padded_sentence] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'facebook/opt-350m' lowerCAmelCase__ :Optional[int] = [ 'Today is a beautiful day and I want to', 'In the city of San Francisco, the city', 'Paris is the capital of France and the capital', 'Computers and mobile phones have taken over the', ] lowerCAmelCase__ :Optional[int] = [] lowerCAmelCase__ :List[Any] = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) for prompt in self.prompts: lowerCAmelCase__ :int = tokenizer(__UpperCAmelCase , return_tensors='tf' ).input_ids lowerCAmelCase__ :str = model.generate(__UpperCAmelCase , max_length=1_0 ) lowerCAmelCase__ :int = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) predicted_outputs += generated_string self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
293
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
1
"""simple docstring""" 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 = """scheduler_config.json""" class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = 1 __magic_name__ :str = 2 __magic_name__ :str = 3 __magic_name__ :Dict = 4 __magic_name__ :int = 5 __magic_name__ :Dict = 6 __magic_name__ :Union[str, Any] = 7 __magic_name__ :Optional[Any] = 8 __magic_name__ :Optional[int] = 9 __magic_name__ :Tuple = 10 __magic_name__ :List[Any] = 11 __magic_name__ :Tuple = 12 __magic_name__ :Union[str, Any] = 13 __magic_name__ :List[str] = 14 @dataclass class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :torch.FloatTensor class _lowerCAmelCase : """simple docstring""" __magic_name__ :Tuple = SCHEDULER_CONFIG_NAME __magic_name__ :int = [] __magic_name__ :int = True @classmethod def snake_case ( cls , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase=False , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = cls.load_config( pretrained_model_name_or_path=__UpperCAmelCase , subfolder=__UpperCAmelCase , return_unused_kwargs=__UpperCAmelCase , return_commit_hash=__UpperCAmelCase , **__UpperCAmelCase , ) return cls.from_config(__UpperCAmelCase , return_unused_kwargs=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = False , **__UpperCAmelCase ): '''simple docstring''' self.save_config(save_directory=__UpperCAmelCase , push_to_hub=__UpperCAmelCase , **__UpperCAmelCase ) @property def snake_case ( self ): '''simple docstring''' return self._get_compatibles() @classmethod def snake_case ( cls ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = list(set([cls.__name__] + cls._compatibles ) ) lowerCAmelCase__ :Any = importlib.import_module(__name__.split('.' )[0] ) lowerCAmelCase__ :List[Any] = [ getattr(__UpperCAmelCase , __UpperCAmelCase ) for c in compatible_classes_str if hasattr(__UpperCAmelCase , __UpperCAmelCase ) ] return compatible_classes
293
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" __A = {"""a""": ["""c""", """b"""], """b""": ["""d""", """e"""], """c""": [], """d""": [], """e""": []} __A = ["""a""", """b""", """c""", """d""", """e"""] def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" lowerCAmelCase__ :Optional[int] = start # add current to visited visited.append(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: lowerCAmelCase__ :Optional[Any] = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(_SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: lowerCAmelCase__ :List[str] = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": __A = topological_sort("""a""", [], []) print(sort)
293
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :UNetaDModel __magic_name__ :KarrasVeScheduler def __init__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' super().__init__() self.register_modules(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) @torch.no_grad() def __call__( self , __UpperCAmelCase = 1 , __UpperCAmelCase = 5_0 , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :int = self.unet.config.sample_size lowerCAmelCase__ :Union[str, Any] = (batch_size, 3, img_size, img_size) lowerCAmelCase__ :Tuple = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) lowerCAmelCase__ :Optional[int] = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(__UpperCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper lowerCAmelCase__ :List[str] = self.scheduler.schedule[t] lowerCAmelCase__ :int = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat lowerCAmelCase__ , lowerCAmelCase__ :int = self.scheduler.add_noise_to_input(__UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. lowerCAmelCase__ :Union[str, Any] = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev lowerCAmelCase__ :List[Any] = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. lowerCAmelCase__ :List[str] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample lowerCAmelCase__ :int = self.scheduler.step_correct( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , step_output.prev_sample , step_output['derivative'] , ) lowerCAmelCase__ :Any = step_output.prev_sample lowerCAmelCase__ :List[Any] = (sample / 2 + 0.5).clamp(0 , 1 ) lowerCAmelCase__ :Union[str, Any] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCAmelCase__ :Optional[Any] = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCAmelCase )
293
"""simple docstring""" 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 _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = 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(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
1
"""simple docstring""" from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __A = {"""UserAgent""": UserAgent().random} def __A (_SCREAMING_SNAKE_CASE ) ->dict: """simple docstring""" lowerCAmelCase__ :Dict = script.contents[0] lowerCAmelCase__ :Any = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = F"https://www.instagram.com/{username}/" lowerCAmelCase__ :Optional[Any] = self.get_json() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = requests.get(self.url , headers=__UpperCAmelCase ).text lowerCAmelCase__ :Dict = BeautifulSoup(__UpperCAmelCase , 'html.parser' ).find_all('script' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): '''simple docstring''' return F"{self.__class__.__name__}('{self.username}')" def __str__( self ): '''simple docstring''' return F"{self.fullname} ({self.username}) is {self.biography}" @property def snake_case ( self ): '''simple docstring''' return self.user_data["username"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["full_name"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["biography"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["business_email"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["external_url"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["is_verified"] @property def snake_case ( self ): '''simple docstring''' return self.user_data["is_private"] def __A (_SCREAMING_SNAKE_CASE = "github" ) ->None: """simple docstring""" import os if os.environ.get('CI' ): return # test failing on GitHub Actions lowerCAmelCase__ :Dict = InstagramUser(_SCREAMING_SNAKE_CASE ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , _SCREAMING_SNAKE_CASE ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 12_0000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('https://instagram.' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __A = InstagramUser("""github""") print(instagram_user) print(F'''{instagram_user.number_of_posts = }''') print(F'''{instagram_user.number_of_followers = }''') print(F'''{instagram_user.number_of_followings = }''') print(F'''{instagram_user.email = }''') print(F'''{instagram_user.website = }''') print(F'''{instagram_user.profile_picture_url = }''') print(F'''{instagram_user.is_verified = }''') print(F'''{instagram_user.is_private = }''')
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset __A = """bert-base-cased""" __A = """google/pegasus-xsum""" __A = [""" Sam ate lunch today.""", """Sams lunch ingredients."""] __A = ["""A very interesting story about what I ate for lunch.""", """Avocado, celery, turkey, coffee"""] __A = """patrickvonplaten/t5-tiny-random""" __A = """sshleifer/bart-tiny-random""" __A = """sshleifer/tiny-mbart""" __A = """sshleifer/tiny-marian-en-de""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = '\n'.join(_SCREAMING_SNAKE_CASE ) Path(_SCREAMING_SNAKE_CASE ).open('w' ).writelines(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Any: """simple docstring""" for split in ["train", "val", "test"]: _dump_articles(os.path.join(_SCREAMING_SNAKE_CASE , F"{split}.source" ) , _SCREAMING_SNAKE_CASE ) _dump_articles(os.path.join(_SCREAMING_SNAKE_CASE , F"{split}.target" ) , _SCREAMING_SNAKE_CASE ) return tmp_dir class _lowerCAmelCase ( a ): """simple docstring""" @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) lowerCAmelCase__ :Optional[Any] = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in ARTICLES ) lowerCAmelCase__ :int = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in SUMMARIES ) lowerCAmelCase__ :Optional[Any] = 4 lowerCAmelCase__ :List[str] = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = 'ro_RO', 'de_DE' # ignored for all but mbart, but never causes error. lowerCAmelCase__ :List[Any] = SeqaSeqDataset( __UpperCAmelCase , data_dir=__UpperCAmelCase , type_path='train' , max_source_length=__UpperCAmelCase , max_target_length=__UpperCAmelCase , src_lang=__UpperCAmelCase , tgt_lang=__UpperCAmelCase , ) lowerCAmelCase__ :Union[str, Any] = DataLoader(__UpperCAmelCase , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place lowerCAmelCase__ :Dict = shift_tokens_right(batch['labels'] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) lowerCAmelCase__ :Any = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in ARTICLES ) lowerCAmelCase__ :Any = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in SUMMARIES ) lowerCAmelCase__ :Optional[Any] = 4 lowerCAmelCase__ :Optional[int] = LegacySeqaSeqDataset( __UpperCAmelCase , data_dir=__UpperCAmelCase , type_path='train' , max_source_length=2_0 , max_target_length=__UpperCAmelCase , ) lowerCAmelCase__ :Dict = DataLoader(__UpperCAmelCase , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 2_0 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained('facebook/mbart-large-cc25' ) lowerCAmelCase__ :Tuple = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) lowerCAmelCase__ :List[Any] = tmp_dir.joinpath('train.source' ).open().readlines() lowerCAmelCase__ :Union[str, Any] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(__UpperCAmelCase , __UpperCAmelCase , 1_2_8 , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = {x.name for x in tmp_dir.iterdir()} lowerCAmelCase__ :Optional[int] = {x.name for x in save_dir.iterdir()} lowerCAmelCase__ :Tuple = save_dir.joinpath('train.source' ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(__UpperCAmelCase ) < len(__UpperCAmelCase ) assert len(__UpperCAmelCase ) == 1 assert len(packed_examples[0] ) == sum(len(__UpperCAmelCase ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='This test requires fairseq' ) def snake_case ( self ): '''simple docstring''' if not FAIRSEQ_AVAILABLE: return lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self._get_dataset(max_len=6_4 ) lowerCAmelCase__ :Tuple = 6_4 lowerCAmelCase__ :List[str] = ds.make_dynamic_sampler(__UpperCAmelCase , required_batch_size_multiple=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = [len(__UpperCAmelCase ) for x in batch_sampler] assert len(set(__UpperCAmelCase ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(__UpperCAmelCase ) == len(__UpperCAmelCase ) # no dropped or added examples lowerCAmelCase__ :Optional[Any] = DataLoader(__UpperCAmelCase , batch_sampler=__UpperCAmelCase , collate_fn=ds.collate_fn , num_workers=2 ) lowerCAmelCase__ :Optional[int] = [] lowerCAmelCase__ :Any = [] for batch in data_loader: lowerCAmelCase__ :int = batch['input_ids'].shape lowerCAmelCase__ :Optional[int] = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple lowerCAmelCase__ :str = np.product(batch['input_ids'].shape ) num_src_per_batch.append(__UpperCAmelCase ) if num_src_tokens > (max_tokens * 1.1): failures.append(__UpperCAmelCase ) assert num_src_per_batch[0] == max(__UpperCAmelCase ) if failures: raise AssertionError(F"too many tokens in {len(__UpperCAmelCase )} batches" ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self._get_dataset(max_len=5_1_2 ) lowerCAmelCase__ :int = 2 lowerCAmelCase__ :int = ds.make_sortish_sampler(__UpperCAmelCase , shuffle=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = DataLoader(__UpperCAmelCase , batch_size=__UpperCAmelCase , collate_fn=ds.collate_fn , num_workers=2 ) lowerCAmelCase__ :List[Any] = DataLoader(__UpperCAmelCase , batch_size=__UpperCAmelCase , collate_fn=ds.collate_fn , num_workers=2 , sampler=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer.pad_token_id def count_pad_tokens(__UpperCAmelCase , __UpperCAmelCase="input_ids" ): return [batch[k].eq(__UpperCAmelCase ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(__UpperCAmelCase , k='labels' ) ) < sum(count_pad_tokens(__UpperCAmelCase , k='labels' ) ) assert sum(count_pad_tokens(__UpperCAmelCase ) ) < sum(count_pad_tokens(__UpperCAmelCase ) ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase=1_0_0_0 , __UpperCAmelCase=1_2_8 ): '''simple docstring''' if os.getenv('USE_REAL_DATA' , __UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = 'examples/seq2seq/wmt_en_ro' lowerCAmelCase__ :Optional[Any] = max_len * 2 * 6_4 if not Path(__UpperCAmelCase ).joinpath('train.len' ).exists(): save_len_file(__UpperCAmelCase , __UpperCAmelCase ) else: lowerCAmelCase__ :List[Any] = 'examples/seq2seq/test_data/wmt_en_ro' lowerCAmelCase__ :Optional[int] = max_len * 4 save_len_file(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Any = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = SeqaSeqDataset( __UpperCAmelCase , data_dir=__UpperCAmelCase , type_path='train' , max_source_length=__UpperCAmelCase , max_target_length=__UpperCAmelCase , n_obs=__UpperCAmelCase , ) return ds, max_tokens, tokenizer def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = self._get_dataset() lowerCAmelCase__ :Dict = set(DistributedSortishSampler(__UpperCAmelCase , 2_5_6 , num_replicas=2 , rank=0 , add_extra_examples=__UpperCAmelCase ) ) lowerCAmelCase__ :Optional[Any] = set(DistributedSortishSampler(__UpperCAmelCase , 2_5_6 , num_replicas=2 , rank=1 , add_extra_examples=__UpperCAmelCase ) ) assert idsa.intersection(__UpperCAmelCase ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = AutoTokenizer.from_pretrained(__UpperCAmelCase , use_fast=__UpperCAmelCase ) if tok_name == MBART_TINY: lowerCAmelCase__ :Tuple = SeqaSeqDataset( __UpperCAmelCase , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , src_lang='EN' , tgt_lang='FR' , ) lowerCAmelCase__ :Any = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: lowerCAmelCase__ :str = SeqaSeqDataset( __UpperCAmelCase , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , ) lowerCAmelCase__ :int = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(__UpperCAmelCase ) == 1 if tok_name == BART_TINY else len(__UpperCAmelCase ) == 0
293
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
1
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :int = (UniPCMultistepScheduler,) __magic_name__ :Union[str, Any] = (("""num_inference_steps""", 25),) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'solver_type': 'bh2', } config.update(**__UpperCAmelCase ) return config def snake_case ( self , __UpperCAmelCase=0 , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dict(self.forward_default_kwargs ) lowerCAmelCase__ :Union[str, Any] = kwargs.pop('num_inference_steps' , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = self.dummy_sample lowerCAmelCase__ :Union[str, Any] = 0.1 * sample lowerCAmelCase__ :int = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowerCAmelCase__ :Any = self.get_scheduler_config(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residuals lowerCAmelCase__ :int = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = scheduler_class.from_pretrained(__UpperCAmelCase ) new_scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residuals lowerCAmelCase__ :int = dummy_past_residuals[: new_scheduler.config.solver_order] lowerCAmelCase__ , lowerCAmelCase__ :int = sample, sample for t in range(__UpperCAmelCase , time_step + scheduler.config.solver_order + 1 ): lowerCAmelCase__ :List[str] = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample lowerCAmelCase__ :Union[str, Any] = new_scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def snake_case ( self , __UpperCAmelCase=0 , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = dict(self.forward_default_kwargs ) lowerCAmelCase__ :Any = kwargs.pop('num_inference_steps' , __UpperCAmelCase ) lowerCAmelCase__ :str = self.dummy_sample lowerCAmelCase__ :List[str] = 0.1 * sample lowerCAmelCase__ :Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowerCAmelCase__ :Optional[Any] = self.get_scheduler_config() lowerCAmelCase__ :Union[str, Any] = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residuals (must be after setting timesteps) lowerCAmelCase__ :Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__UpperCAmelCase ) lowerCAmelCase__ :Any = scheduler_class.from_pretrained(__UpperCAmelCase ) # copy over dummy past residuals new_scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residual (must be after setting timesteps) lowerCAmelCase__ :str = dummy_past_residuals[: new_scheduler.config.solver_order] lowerCAmelCase__ :int = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample lowerCAmelCase__ :Optional[Any] = new_scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def snake_case ( self , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' if scheduler is None: lowerCAmelCase__ :Optional[int] = self.scheduler_classes[0] lowerCAmelCase__ :List[Any] = self.get_scheduler_config(**__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = scheduler_class(**__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self.scheduler_classes[0] lowerCAmelCase__ :Optional[int] = self.get_scheduler_config(**__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = scheduler_class(**__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = 1_0 lowerCAmelCase__ :Tuple = self.dummy_model() lowerCAmelCase__ :int = self.dummy_sample_deter scheduler.set_timesteps(__UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ :List[str] = model(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample return sample def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = dict(self.forward_default_kwargs ) lowerCAmelCase__ :Union[str, Any] = kwargs.pop('num_inference_steps' , __UpperCAmelCase ) for scheduler_class in self.scheduler_classes: lowerCAmelCase__ :Optional[Any] = self.get_scheduler_config() lowerCAmelCase__ :Dict = scheduler_class(**__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self.dummy_sample lowerCAmelCase__ :Optional[Any] = 0.1 * sample if num_inference_steps is not None and hasattr(__UpperCAmelCase , 'set_timesteps' ): scheduler.set_timesteps(__UpperCAmelCase ) elif num_inference_steps is not None and not hasattr(__UpperCAmelCase , 'set_timesteps' ): lowerCAmelCase__ :List[str] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) lowerCAmelCase__ :Tuple = [residual + 0.2, residual + 0.15, residual + 0.10] lowerCAmelCase__ :List[Any] = dummy_past_residuals[: scheduler.config.solver_order] lowerCAmelCase__ :Optional[int] = scheduler.timesteps[5] lowerCAmelCase__ :Optional[int] = scheduler.timesteps[6] lowerCAmelCase__ :str = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample lowerCAmelCase__ :List[str] = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = UniPCMultistepScheduler(**self.get_scheduler_config() ) lowerCAmelCase__ :Optional[int] = self.full_loop(scheduler=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_mean.item() - 0.24_64 ) < 1E-3 lowerCAmelCase__ :Optional[int] = DPMSolverSinglestepScheduler.from_config(scheduler.config ) lowerCAmelCase__ :List[Any] = DEISMultistepScheduler.from_config(scheduler.config ) lowerCAmelCase__ :List[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config ) lowerCAmelCase__ :Optional[Any] = UniPCMultistepScheduler.from_config(scheduler.config ) lowerCAmelCase__ :str = self.full_loop(scheduler=__UpperCAmelCase ) lowerCAmelCase__ :int = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_mean.item() - 0.24_64 ) < 1E-3 def snake_case ( self ): '''simple docstring''' for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.check_over_configs(thresholding=__UpperCAmelCase ) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__UpperCAmelCase , prediction_type=__UpperCAmelCase , sample_max_value=__UpperCAmelCase , solver_order=__UpperCAmelCase , solver_type=__UpperCAmelCase , ) def snake_case ( self ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__UpperCAmelCase , solver_type=__UpperCAmelCase , prediction_type=__UpperCAmelCase , ) lowerCAmelCase__ :List[str] = self.full_loop( solver_order=__UpperCAmelCase , solver_type=__UpperCAmelCase , prediction_type=__UpperCAmelCase , ) assert not torch.isnan(__UpperCAmelCase ).any(), "Samples have nan numbers" def snake_case ( self ): '''simple docstring''' self.check_over_configs(lower_order_final=__UpperCAmelCase ) self.check_over_configs(lower_order_final=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=__UpperCAmelCase , time_step=0 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.full_loop() lowerCAmelCase__ :Dict = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_mean.item() - 0.24_64 ) < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.full_loop(prediction_type='v_prediction' ) lowerCAmelCase__ :List[str] = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_mean.item() - 0.10_14 ) < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.scheduler_classes[0] lowerCAmelCase__ :int = self.get_scheduler_config(thresholding=__UpperCAmelCase , dynamic_thresholding_ratio=0 ) lowerCAmelCase__ :List[Any] = scheduler_class(**__UpperCAmelCase ) lowerCAmelCase__ :int = 1_0 lowerCAmelCase__ :Any = self.dummy_model() lowerCAmelCase__ :Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(__UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ :Any = model(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample assert sample.dtype == torch.floataa def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' for scheduler_class in self.scheduler_classes: lowerCAmelCase__ :int = self.get_scheduler_config(**__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or number < 0: raise ValueError('Input must be a non-negative integer' ) lowerCAmelCase__ :Dict = 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()
293
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
1
"""simple docstring""" import numpy as np from transformers import Pipeline def __A (_SCREAMING_SNAKE_CASE ) ->Any: """simple docstring""" lowerCAmelCase__ :Any = np.max(_SCREAMING_SNAKE_CASE , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = {} if "second_text" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['second_text'] return preprocess_kwargs, {}, {} def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None ): '''simple docstring''' return self.tokenizer(__UpperCAmelCase , text_pair=__UpperCAmelCase , return_tensors=self.framework ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = model_outputs.logits[0].numpy() lowerCAmelCase__ :Dict = softmax(__UpperCAmelCase ) lowerCAmelCase__ :str = np.argmax(__UpperCAmelCase ) lowerCAmelCase__ :int = self.model.config.idalabel[best_class] lowerCAmelCase__ :Tuple = probabilities[best_class].item() lowerCAmelCase__ :int = logits.tolist() return {"label": label, "score": score, "logits": logits}
293
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
1
"""simple docstring""" import csv import tweepy # Twitter API credentials __A = """""" __A = """""" __A = """""" __A = """""" def __A (_SCREAMING_SNAKE_CASE ) ->None: """simple docstring""" lowerCAmelCase__ :Optional[Any] = tweepy.OAuthHandler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) auth.set_access_token(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = tweepy.API(_SCREAMING_SNAKE_CASE ) # initialize a list to hold all the tweepy Tweets lowerCAmelCase__ :str = [] # make initial request for most recent tweets (200 is the maximum allowed count) lowerCAmelCase__ :Optional[int] = api.user_timeline(screen_name=_SCREAMING_SNAKE_CASE , count=200 ) # save most recent tweets alltweets.extend(_SCREAMING_SNAKE_CASE ) # save the id of the oldest tweet less one lowerCAmelCase__ :Union[str, Any] = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(_SCREAMING_SNAKE_CASE ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates lowerCAmelCase__ :Union[str, Any] = api.user_timeline( screen_name=_SCREAMING_SNAKE_CASE , count=200 , max_id=_SCREAMING_SNAKE_CASE ) # save most recent tweets alltweets.extend(_SCREAMING_SNAKE_CASE ) # update the id of the oldest tweet less one lowerCAmelCase__ :Any = alltweets[-1].id - 1 print(F"...{len(_SCREAMING_SNAKE_CASE )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv lowerCAmelCase__ :Optional[Any] = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: lowerCAmelCase__ :List[str] = csv.writer(_SCREAMING_SNAKE_CASE ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
293
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
1
"""simple docstring""" import sys __A = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" lowerCAmelCase__ :Any = 1 for digit in s: product *= int(_SCREAMING_SNAKE_CASE ) return product def __A (_SCREAMING_SNAKE_CASE = N ) ->int: """simple docstring""" lowerCAmelCase__ :str = -sys.maxsize - 1 lowerCAmelCase__ :List[Any] = n[:13] lowerCAmelCase__ :Optional[int] = 13 while cur_index < len(_SCREAMING_SNAKE_CASE ) - 13: if int(n[cur_index] ) >= int(substr[0] ): lowerCAmelCase__ :Any = substr[1:] + n[cur_index] cur_index += 1 else: lowerCAmelCase__ :Tuple = max(_SCREAMING_SNAKE_CASE , str_eval(_SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ :List[Any] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(F'''{solution() = }''')
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor __A = logging.get_logger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def __A (_SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" lowerCAmelCase__ :int = checkpoints.load_tax_checkpoint(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = flatten_dict(_SCREAMING_SNAKE_CASE ) return flax_params def __A (_SCREAMING_SNAKE_CASE ) ->Any: """simple docstring""" lowerCAmelCase__ :Any = {} lowerCAmelCase__ :List[str] = { 'token_embedder': 'embeddings', 'encoder_norm': 'layernorm', 'kernel': 'weight', '.out': '.output', 'scale': 'weight', 'embedders_0.pos_embedding': 'row_embedder.weight', 'embedders_1.pos_embedding': 'column_embedder.weight', } lowerCAmelCase__ :str = { 'query': 'attention.query', 'key': 'attention.key', 'value': 'attention.value', 'output.dense': 'output', 'encoder_decoder_attention.o': 'encoder_decoder_attention.attention.o', 'pre_self_attention_layer_norm': 'self_attention.layer_norm', 'pre_cross_attention_layer_norm': 'encoder_decoder_attention.layer_norm', 'mlp.': 'mlp.DenseReluDense.', 'pre_mlp_layer_norm': 'mlp.layer_norm', 'self_attention.o': 'self_attention.attention.o', 'decoder.embeddings.embedding': 'decoder.embed_tokens.weight', 'decoder.relpos_bias.rel_embedding': 'decoder.layer.0.self_attention.attention.relative_attention_bias.weight', 'decoder.decoder_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.logits_dense.weight': 'decoder.lm_head.weight', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key lowerCAmelCase__ :List[Any] = '.'.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): lowerCAmelCase__ :Any = new_key.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): lowerCAmelCase__ :List[Any] = new_key.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number lowerCAmelCase__ :int = re.sub(r'layers_(\d+)' , r'layer.\1' , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = new_key.replace('encoder' , 'encoder.encoder' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number lowerCAmelCase__ :Dict = re.sub(r'layers_(\d+)' , r'layer.\1' , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = flax_dict[key] lowerCAmelCase__ :List[str] = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): lowerCAmelCase__ :Any = torch.from_numpy(converted_dict[key].T ) else: lowerCAmelCase__ :List[Any] = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ) ->str: """simple docstring""" lowerCAmelCase__ :Any = get_flax_param(_SCREAMING_SNAKE_CASE ) if not use_large: lowerCAmelCase__ :List[str] = PixaStructVisionConfig() lowerCAmelCase__ :Tuple = PixaStructTextConfig() else: lowerCAmelCase__ :Union[str, Any] = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) lowerCAmelCase__ :List[str] = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) lowerCAmelCase__ :Union[str, Any] = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = PixaStructForConditionalGeneration(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = rename_and_convert_flax_params(_SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Tuple = AutoTokenizer.from_pretrained('ybelkada/test-pix2struct-tokenizer' ) lowerCAmelCase__ :Union[str, Any] = PixaStructImageProcessor() lowerCAmelCase__ :Union[str, Any] = PixaStructProcessor(image_processor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) if use_large: lowerCAmelCase__ :Tuple = 4096 lowerCAmelCase__ :Dict = True # mkdir if needed os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) print('Model saved in {}'.format(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument("""--t5x_checkpoint_path""", default=None, type=str, help="""Path to the original T5x checkpoint.""") parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--use_large""", action="""store_true""", help="""Use large model.""") parser.add_argument("""--is_vqa""", action="""store_true""", help="""Use large model.""") __A = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
293
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( 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 _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" 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 = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = 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' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
1
"""simple docstring""" import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Any = IFInpaintingSuperResolutionPipeline __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""width""", """height"""} __magic_name__ :List[str] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"""original_image"""} ) __magic_name__ :List[str] = PipelineTesterMixin.required_optional_params - {"""latents"""} def snake_case ( self ): '''simple docstring''' return self._get_superresolution_dummy_components() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Tuple = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[int] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'original_image': original_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs @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 ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def snake_case ( self ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' ) def snake_case ( self ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def snake_case ( self ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def snake_case ( self ): '''simple docstring''' self._test_save_load_local() def snake_case ( self ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
293
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
1
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE ) ->list: """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) <= 1: return [tuple(_SCREAMING_SNAKE_CASE )] lowerCAmelCase__ :Optional[Any] = [] def generate(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = [0] * n res.append(tuple(_SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ :Union[str, Any] = 0 while i < n: if c[i] < i: if i % 2 == 0: lowerCAmelCase__ , lowerCAmelCase__ :str = arr[i], arr[0] else: lowerCAmelCase__ , lowerCAmelCase__ :Dict = arr[i], arr[c[i]] res.append(tuple(_SCREAMING_SNAKE_CASE ) ) c[i] += 1 lowerCAmelCase__ :Any = 0 else: lowerCAmelCase__ :List[Any] = 0 i += 1 generate(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": __A = input("""Enter numbers separated by a comma:\n""").strip() __A = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
293
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
1
"""simple docstring""" 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 _lowerCAmelCase : """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' return None class _lowerCAmelCase : """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' return None class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :Dict = [ # (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 ): '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__UpperCAmelCase , 'tf' , 1_2 , **__UpperCAmelCase ) @require_torch @slow def snake_case ( self ): '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__UpperCAmelCase , 'pt' , 1_2 , **__UpperCAmelCase ) @require_torch @slow def snake_case ( self ): '''simple docstring''' from transformers import BertModel lowerCAmelCase__ :Tuple = ['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words'] with NamedTemporaryFile(mode='w+t' ) as vocab_file: vocab_file.write('\n'.join(__UpperCAmelCase ) ) vocab_file.flush() lowerCAmelCase__ :Optional[int] = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: lowerCAmelCase__ :Dict = BertModel(BertConfig(vocab_size=len(__UpperCAmelCase ) ) ) model.save_pretrained(__UpperCAmelCase ) self._test_export(__UpperCAmelCase , 'pt' , 1_2 , __UpperCAmelCase ) @require_tf @slow def snake_case ( self ): '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowerCAmelCase__ :Any = self._test_export(__UpperCAmelCase , 'tf' , 1_2 , **__UpperCAmelCase ) lowerCAmelCase__ :Any = quantize(Path(__UpperCAmelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__UpperCAmelCase ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) @require_torch @slow def snake_case ( self ): '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowerCAmelCase__ :Tuple = self._test_export(__UpperCAmelCase , 'pt' , 1_2 , **__UpperCAmelCase ) lowerCAmelCase__ :str = quantize(__UpperCAmelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__UpperCAmelCase ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' try: # Compute path with TemporaryDirectory() as tempdir: lowerCAmelCase__ :Union[str, Any] = Path(__UpperCAmelCase ).joinpath('model.onnx' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ) return path except Exception as e: self.fail(__UpperCAmelCase ) @require_torch @require_tokenizers @slow def snake_case ( self ): '''simple docstring''' from transformers import BertModel lowerCAmelCase__ :List[Any] = BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) lowerCAmelCase__ :Union[str, Any] = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(__UpperCAmelCase , __UpperCAmelCase , 'pt' ) @require_tf @require_tokenizers @slow def snake_case ( self ): '''simple docstring''' from transformers import TFBertModel lowerCAmelCase__ :Any = TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) lowerCAmelCase__ :Dict = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(__UpperCAmelCase , __UpperCAmelCase , 'tf' ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = FeatureExtractionPipeline(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Dict = ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = infer_shapes(__UpperCAmelCase , __UpperCAmelCase ) # Assert all variables are present self.assertEqual(len(__UpperCAmelCase ) , len(__UpperCAmelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __UpperCAmelCase ) self.assertSequenceEqual(variable_names[3:] , __UpperCAmelCase ) # 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 ): '''simple docstring''' lowerCAmelCase__ :Tuple = ['input_ids', 'attention_mask', 'token_type_ids'] lowerCAmelCase__ :int = {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]} lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = ensure_valid_input(FuncContiguousArgs() , __UpperCAmelCase , __UpperCAmelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__UpperCAmelCase ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__UpperCAmelCase ) , set(__UpperCAmelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__UpperCAmelCase , (tokens['input_ids'], tokens['token_type_ids'], tokens['attention_mask']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) lowerCAmelCase__ , lowerCAmelCase__ :Tuple = ensure_valid_input(FuncNonContiguousArgs() , __UpperCAmelCase , __UpperCAmelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__UpperCAmelCase ) , 1 ) self.assertEqual(len(__UpperCAmelCase ) , 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 ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = generate_identified_filename(Path('/home/something/my_fake_model.onnx' ) , '-test' ) self.assertEqual('/home/something/my_fake_model-test.onnx' , generated.as_posix() )
293
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], '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]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
1
"""simple docstring""" import gc import math import unittest import torch from diffusers import UNetaDModel from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin __A = logging.get_logger(__name__) enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Optional[Any] = UNetaDModel __magic_name__ :int = """sample""" @property def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 4 lowerCAmelCase__ :List[Any] = 3 lowerCAmelCase__ :Dict = (3_2, 3_2) lowerCAmelCase__ :int = floats_tensor((batch_size, num_channels) + sizes ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = torch.tensor([1_0] ).to(__UpperCAmelCase ) return {"sample": noise, "timestep": time_step} @property def snake_case ( self ): '''simple docstring''' return (3, 3_2, 3_2) @property def snake_case ( self ): '''simple docstring''' return (3, 3_2, 3_2) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = { 'block_out_channels': (3_2, 6_4), 'down_block_types': ('DownBlock2D', 'AttnDownBlock2D'), 'up_block_types': ('AttnUpBlock2D', 'UpBlock2D'), 'attention_head_dim': 3, 'out_channels': 3, 'in_channels': 3, 'layers_per_block': 2, 'sample_size': 3_2, } lowerCAmelCase__ :int = self.dummy_input return init_dict, inputs_dict class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Dict = UNetaDModel __magic_name__ :Dict = """sample""" @property def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 4 lowerCAmelCase__ :int = 4 lowerCAmelCase__ :List[Any] = (3_2, 3_2) lowerCAmelCase__ :List[str] = floats_tensor((batch_size, num_channels) + sizes ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1_0] ).to(__UpperCAmelCase ) return {"sample": noise, "timestep": time_step} @property def snake_case ( self ): '''simple docstring''' return (4, 3_2, 3_2) @property def snake_case ( self ): '''simple docstring''' return (4, 3_2, 3_2) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = { 'sample_size': 3_2, 'in_channels': 4, 'out_channels': 4, 'layers_per_block': 2, 'block_out_channels': (3_2, 6_4), 'attention_head_dim': 3_2, 'down_block_types': ('DownBlock2D', 'DownBlock2D'), 'up_block_types': ('UpBlock2D', 'UpBlock2D'), } lowerCAmelCase__ :Optional[int] = self.dummy_input return init_dict, inputs_dict def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :str = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' , output_loading_info=__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != 'cuda' , 'This test is supposed to run on GPU' ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' , output_loading_info=__UpperCAmelCase ) model.to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != 'cuda' , 'This test is supposed to run on GPU' ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :str = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' , output_loading_info=__UpperCAmelCase ) model_accelerate.to(__UpperCAmelCase ) model_accelerate.eval() lowerCAmelCase__ :List[str] = torch.randn( 1 , model_accelerate.config.in_channels , model_accelerate.config.sample_size , model_accelerate.config.sample_size , generator=torch.manual_seed(0 ) , ) lowerCAmelCase__ :Dict = noise.to(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = torch.tensor([1_0] * noise.shape[0] ).to(__UpperCAmelCase ) lowerCAmelCase__ :Any = model_accelerate(__UpperCAmelCase , __UpperCAmelCase )['sample'] # two models don't need to stay in the device at the same time del model_accelerate torch.cuda.empty_cache() gc.collect() lowerCAmelCase__ , lowerCAmelCase__ :List[str] = UNetaDModel.from_pretrained( 'fusing/unet-ldm-dummy-update' , output_loading_info=__UpperCAmelCase , low_cpu_mem_usage=__UpperCAmelCase ) model_normal_load.to(__UpperCAmelCase ) model_normal_load.eval() lowerCAmelCase__ :List[Any] = model_normal_load(__UpperCAmelCase , __UpperCAmelCase )['sample'] assert torch_all_close(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-3 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' ) model.eval() model.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) lowerCAmelCase__ :str = noise.to(__UpperCAmelCase ) lowerCAmelCase__ :Any = torch.tensor([1_0] * noise.shape[0] ).to(__UpperCAmelCase ) with torch.no_grad(): lowerCAmelCase__ :Union[str, Any] = model(__UpperCAmelCase , __UpperCAmelCase ).sample lowerCAmelCase__ :str = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off lowerCAmelCase__ :Union[str, Any] = torch.tensor([-13.32_58, -20.11_00, -15.98_73, -17.66_17, -23.05_96, -17.94_19, -13.36_75, -16.18_89, -12.38_00] ) # fmt: on self.assertTrue(torch_all_close(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-3 ) ) class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Dict = UNetaDModel __magic_name__ :Optional[Any] = """sample""" @property def snake_case ( self , __UpperCAmelCase=(3_2, 3_2) ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 4 lowerCAmelCase__ :Union[str, Any] = 3 lowerCAmelCase__ :List[Any] = floats_tensor((batch_size, num_channels) + sizes ).to(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = torch.tensor(batch_size * [1_0] ).to(dtype=torch.intaa , device=__UpperCAmelCase ) return {"sample": noise, "timestep": time_step} @property def snake_case ( self ): '''simple docstring''' return (3, 3_2, 3_2) @property def snake_case ( self ): '''simple docstring''' return (3, 3_2, 3_2) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = { 'block_out_channels': [3_2, 6_4, 6_4, 6_4], 'in_channels': 3, 'layers_per_block': 1, 'out_channels': 3, 'time_embedding_type': 'fourier', 'norm_eps': 1E-6, 'mid_block_scale_factor': math.sqrt(2.0 ), 'norm_num_groups': None, 'down_block_types': [ 'SkipDownBlock2D', 'AttnSkipDownBlock2D', 'SkipDownBlock2D', 'SkipDownBlock2D', ], 'up_block_types': [ 'SkipUpBlock2D', 'SkipUpBlock2D', 'AttnSkipUpBlock2D', 'SkipUpBlock2D', ], } lowerCAmelCase__ :Optional[Any] = self.dummy_input return init_dict, inputs_dict @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = UNetaDModel.from_pretrained('google/ncsnpp-celebahq-256' , output_loading_info=__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = self.dummy_input lowerCAmelCase__ :List[Any] = floats_tensor((4, 3) + (2_5_6, 2_5_6) ).to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = noise lowerCAmelCase__ :int = model(**__UpperCAmelCase ) assert image is not None, "Make sure output is not None" @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = UNetaDModel.from_pretrained('google/ncsnpp-celebahq-256' ) model.to(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = 4 lowerCAmelCase__ :List[Any] = 3 lowerCAmelCase__ :List[str] = (2_5_6, 2_5_6) lowerCAmelCase__ :Union[str, Any] = torch.ones((batch_size, num_channels) + sizes ).to(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.tensor(batch_size * [1E-4] ).to(__UpperCAmelCase ) with torch.no_grad(): lowerCAmelCase__ :Union[str, Any] = model(__UpperCAmelCase , __UpperCAmelCase ).sample lowerCAmelCase__ :Union[str, Any] = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off lowerCAmelCase__ :List[str] = torch.tensor([-48_42.86_91, -64_99.66_31, -38_00.19_53, -79_78.26_86, -1_09_80.71_29, -2_00_28.85_35, 81_48.28_22, 23_42.29_05, 5_67.76_08] ) # fmt: on self.assertTrue(torch_all_close(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-2 ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = UNetaDModel.from_pretrained('fusing/ncsnpp-ffhq-ve-dummy-update' ) model.to(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = 4 lowerCAmelCase__ :List[Any] = 3 lowerCAmelCase__ :Tuple = (3_2, 3_2) lowerCAmelCase__ :Tuple = torch.ones((batch_size, num_channels) + sizes ).to(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = torch.tensor(batch_size * [1E-4] ).to(__UpperCAmelCase ) with torch.no_grad(): lowerCAmelCase__ :str = model(__UpperCAmelCase , __UpperCAmelCase ).sample lowerCAmelCase__ :Optional[Any] = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off lowerCAmelCase__ :Optional[int] = torch.tensor([-0.03_25, -0.09_00, -0.08_69, -0.03_32, -0.07_25, -0.02_70, -0.01_01, 0.02_27, 0.02_56] ) # fmt: on self.assertTrue(torch_all_close(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-2 ) ) def snake_case ( self ): '''simple docstring''' pass
293
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" def get_masked_lm_array(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE" lowerCAmelCase__ :Dict = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if "kernel" in name: lowerCAmelCase__ :Tuple = array.transpose() return torch.from_numpy(_SCREAMING_SNAKE_CASE ) def get_encoder_array(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE" lowerCAmelCase__ :Tuple = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if "kernel" in name: lowerCAmelCase__ :Dict = array.transpose() return torch.from_numpy(_SCREAMING_SNAKE_CASE ) def get_encoder_layer_array(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE" lowerCAmelCase__ :List[str] = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if "kernel" in name: lowerCAmelCase__ :Union[str, Any] = array.transpose() return torch.from_numpy(_SCREAMING_SNAKE_CASE ) def get_encoder_attention_layer_array(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE" lowerCAmelCase__ :Optional[Any] = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = array.reshape(_SCREAMING_SNAKE_CASE ) if "kernel" in name: lowerCAmelCase__ :Tuple = array.transpose() return torch.from_numpy(_SCREAMING_SNAKE_CASE ) print(F"Loading model based on config from {config_path}..." ) lowerCAmelCase__ :Optional[Any] = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = BertForMaskedLM(_SCREAMING_SNAKE_CASE ) # Layers for layer_index in range(0 , config.num_hidden_layers ): lowerCAmelCase__ :BertLayer = model.bert.encoder.layer[layer_index] # Self-attention lowerCAmelCase__ :BertSelfAttention = layer.attention.self lowerCAmelCase__ :int = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_query_dense/kernel' , self_attn.query.weight.data.shape ) lowerCAmelCase__ :str = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_query_dense/bias' , self_attn.query.bias.data.shape ) lowerCAmelCase__ :Tuple = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_key_dense/kernel' , self_attn.key.weight.data.shape ) lowerCAmelCase__ :Dict = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_key_dense/bias' , self_attn.key.bias.data.shape ) lowerCAmelCase__ :List[str] = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_value_dense/kernel' , self_attn.value.weight.data.shape ) lowerCAmelCase__ :Dict = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_value_dense/bias' , self_attn.value.bias.data.shape ) # Self-attention Output lowerCAmelCase__ :BertSelfOutput = layer.attention.output lowerCAmelCase__ :List[Any] = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_output_dense/kernel' , self_output.dense.weight.data.shape ) lowerCAmelCase__ :str = get_encoder_attention_layer_array( _SCREAMING_SNAKE_CASE , '_output_dense/bias' , self_output.dense.bias.data.shape ) lowerCAmelCase__ :List[str] = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_attention_layer_norm/gamma' ) lowerCAmelCase__ :List[str] = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_attention_layer_norm/beta' ) # Intermediate lowerCAmelCase__ :BertIntermediate = layer.intermediate lowerCAmelCase__ :Optional[int] = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_intermediate_dense/kernel' ) lowerCAmelCase__ :Dict = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_intermediate_dense/bias' ) # Output lowerCAmelCase__ :BertOutput = layer.output lowerCAmelCase__ :Any = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_output_dense/kernel' ) lowerCAmelCase__ :Optional[int] = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_output_dense/bias' ) lowerCAmelCase__ :Any = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_output_layer_norm/gamma' ) lowerCAmelCase__ :Optional[Any] = get_encoder_layer_array(_SCREAMING_SNAKE_CASE , '_output_layer_norm/beta' ) # Embeddings lowerCAmelCase__ :int = get_encoder_array('_position_embedding_layer/embeddings' ) lowerCAmelCase__ :Optional[Any] = get_encoder_array('_type_embedding_layer/embeddings' ) lowerCAmelCase__ :Union[str, Any] = get_encoder_array('_embedding_norm_layer/gamma' ) lowerCAmelCase__ :Optional[Any] = get_encoder_array('_embedding_norm_layer/beta' ) # LM Head lowerCAmelCase__ :Optional[Any] = model.cls.predictions.transform lowerCAmelCase__ :Optional[Any] = get_masked_lm_array('dense/kernel' ) lowerCAmelCase__ :Dict = get_masked_lm_array('dense/bias' ) lowerCAmelCase__ :Tuple = get_masked_lm_array('layer_norm/gamma' ) lowerCAmelCase__ :Dict = get_masked_lm_array('layer_norm/beta' ) lowerCAmelCase__ :Union[str, Any] = get_masked_lm_array('embedding_table' ) # Pooling lowerCAmelCase__ :Tuple = BertPooler(config=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :BertPooler = get_encoder_array('_pooler_layer/kernel' ) lowerCAmelCase__ :BertPooler = get_encoder_array('_pooler_layer/bias' ) # Export final model model.save_pretrained(_SCREAMING_SNAKE_CASE ) # Integration test - should load without any errors ;) lowerCAmelCase__ :Optional[Any] = BertForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE ) print(new_model.eval() ) print('Model conversion was done sucessfully!' ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( """--tf_checkpoint_path""", type=str, required=True, help="""Path to the TensorFlow Token Dropping checkpoint path.""" ) parser.add_argument( """--bert_config_file""", type=str, required=True, help="""The config json file corresponding to the BERT model. This specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", type=str, required=True, help="""Path to the output PyTorch model.""", ) __A = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
1
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml __A = NewType("""DataClass""", Any) __A = NewType("""DataClassType""", Any) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)." ) def __A (_SCREAMING_SNAKE_CASE ) ->Callable[[str], Any]: """simple docstring""" lowerCAmelCase__ :str = {str(_SCREAMING_SNAKE_CASE ): choice for choice in choices} return lambda _SCREAMING_SNAKE_CASE : str_to_choice.get(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __A (*, _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = dataclasses.MISSING , _SCREAMING_SNAKE_CASE = dataclasses.MISSING , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) ->dataclasses.Field: """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls lowerCAmelCase__ :List[Any] = {} if aliases is not None: lowerCAmelCase__ :Optional[Any] = aliases if help is not None: lowerCAmelCase__ :int = help return dataclasses.field(metadata=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , default_factory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Iterable[DataClassType] def __init__( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' if "formatter_class" not in kwargs: lowerCAmelCase__ :Tuple = ArgumentDefaultsHelpFormatter super().__init__(**__UpperCAmelCase ) if dataclasses.is_dataclass(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = [dataclass_types] lowerCAmelCase__ :List[str] = list(__UpperCAmelCase ) for dtype in self.dataclass_types: self._add_dataclass_arguments(__UpperCAmelCase ) @staticmethod def snake_case ( __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = F"--{field.name}" lowerCAmelCase__ :Dict = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , __UpperCAmelCase ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) lowerCAmelCase__ :int = kwargs.pop('aliases' , [] ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :int = [aliases] lowerCAmelCase__ :Optional[Any] = getattr(field.type , '__origin__' , field.type ) if origin_type is Union or (hasattr(__UpperCAmelCase , 'UnionType' ) and isinstance(__UpperCAmelCase , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(__UpperCAmelCase ) not in field.type.__args__ ): raise ValueError( 'Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because' ' the argument parser only supports one type per argument.' F" Problem encountered in field '{field.name}'." ) if type(__UpperCAmelCase ) not in field.type.__args__: # filter `str` in Union lowerCAmelCase__ :Optional[Any] = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] lowerCAmelCase__ :Tuple = getattr(field.type , '__origin__' , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) lowerCAmelCase__ :Optional[int] = ( field.type.__args__[0] if isinstance(__UpperCAmelCase , field.type.__args__[1] ) else field.type.__args__[1] ) lowerCAmelCase__ :Any = getattr(field.type , '__origin__' , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) lowerCAmelCase__ :Dict = {} if origin_type is Literal or (isinstance(field.type , __UpperCAmelCase ) and issubclass(field.type , __UpperCAmelCase )): if origin_type is Literal: lowerCAmelCase__ :Dict = field.type.__args__ else: lowerCAmelCase__ :Dict = [x.value for x in field.type] lowerCAmelCase__ :Any = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: lowerCAmelCase__ :int = field.default else: lowerCAmelCase__ :Any = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument lowerCAmelCase__ :Optional[int] = copy(__UpperCAmelCase ) # Hack because type=bool in argparse does not behave as we want. lowerCAmelCase__ :Dict = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. lowerCAmelCase__ :Union[str, Any] = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way lowerCAmelCase__ :Any = default # This tells argparse we accept 0 or 1 value after --field_name lowerCAmelCase__ :Any = '?' # This is the value that will get picked if we do --field_name (without value) lowerCAmelCase__ :int = True elif isclass(__UpperCAmelCase ) and issubclass(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :List[Any] = field.type.__args__[0] lowerCAmelCase__ :Union[str, Any] = '+' if field.default_factory is not dataclasses.MISSING: lowerCAmelCase__ :str = field.default_factory() elif field.default is dataclasses.MISSING: lowerCAmelCase__ :Optional[Any] = True else: lowerCAmelCase__ :Dict = field.type if field.default is not dataclasses.MISSING: lowerCAmelCase__ :List[str] = field.default elif field.default_factory is not dataclasses.MISSING: lowerCAmelCase__ :Optional[Any] = field.default_factory() else: lowerCAmelCase__ :Optional[Any] = True parser.add_argument(__UpperCAmelCase , *__UpperCAmelCase , **__UpperCAmelCase ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): lowerCAmelCase__ :int = False parser.add_argument(F"--no_{field.name}" , action='store_false' , dest=field.name , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if hasattr(__UpperCAmelCase , '_argument_group_name' ): lowerCAmelCase__ :Optional[int] = self.add_argument_group(dtype._argument_group_name ) else: lowerCAmelCase__ :Union[str, Any] = self try: lowerCAmelCase__ :Dict[str, type] = get_type_hints(__UpperCAmelCase ) except NameError: raise RuntimeError( F"Type resolution failed for {dtype}. Try declaring the class in global scope or " 'removing line of `from __future__ import annotations` which opts in Postponed ' 'Evaluation of Annotations (PEP 563)' ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 1_0) and "unsupported operand type(s) for |" in str(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = '.'.join(map(__UpperCAmelCase , sys.version_info[:3] ) ) raise RuntimeError( F"Type resolution failed for {dtype} on Python {python_version}. Try removing " 'line of `from __future__ import annotations` which opts in union types as ' '`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To ' 'support Python versions that lower than 3.10, you need to use ' '`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of ' '`X | None`.' ) from ex raise for field in dataclasses.fields(__UpperCAmelCase ): if not field.init: continue lowerCAmelCase__ :List[Any] = type_hints[field.name] self._parse_dataclass_field(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=None , ): '''simple docstring''' if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): lowerCAmelCase__ :List[Any] = [] if args_filename: args_files.append(Path(__UpperCAmelCase ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix('.args' ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values lowerCAmelCase__ :List[Any] = ArgumentParser() args_file_parser.add_argument(__UpperCAmelCase , type=__UpperCAmelCase , action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) lowerCAmelCase__ , lowerCAmelCase__ :Any = args_file_parser.parse_known_args(args=__UpperCAmelCase ) lowerCAmelCase__ :Any = vars(__UpperCAmelCase ).get(args_file_flag.lstrip('-' ) , __UpperCAmelCase ) if cmd_args_file_paths: args_files.extend([Path(__UpperCAmelCase ) for p in cmd_args_file_paths] ) lowerCAmelCase__ :Tuple = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last lowerCAmelCase__ :List[str] = file_args + args if args is not None else file_args + sys.argv[1:] lowerCAmelCase__ , lowerCAmelCase__ :str = self.parse_known_args(args=__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [] for dtype in self.dataclass_types: lowerCAmelCase__ :List[Any] = {f.name for f in dataclasses.fields(__UpperCAmelCase ) if f.init} lowerCAmelCase__ :Optional[Any] = {k: v for k, v in vars(__UpperCAmelCase ).items() if k in keys} for k in keys: delattr(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = dtype(**__UpperCAmelCase ) outputs.append(__UpperCAmelCase ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(__UpperCAmelCase ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F"Some specified arguments are not used by the HfArgumentParser: {remaining_args}" ) return (*outputs,) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = False ): '''simple docstring''' lowerCAmelCase__ :str = set(args.keys() ) lowerCAmelCase__ :Optional[Any] = [] for dtype in self.dataclass_types: lowerCAmelCase__ :Any = {f.name for f in dataclasses.fields(__UpperCAmelCase ) if f.init} lowerCAmelCase__ :str = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) lowerCAmelCase__ :List[Any] = dtype(**__UpperCAmelCase ) outputs.append(__UpperCAmelCase ) if not allow_extra_keys and unused_keys: raise ValueError(F"Some keys are not used by the HfArgumentParser: {sorted(__UpperCAmelCase )}" ) return tuple(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = False ): '''simple docstring''' with open(Path(__UpperCAmelCase ) , encoding='utf-8' ) as open_json_file: lowerCAmelCase__ :Dict = json.loads(open_json_file.read() ) lowerCAmelCase__ :int = self.parse_dict(__UpperCAmelCase , allow_extra_keys=__UpperCAmelCase ) return tuple(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = False ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.parse_dict(yaml.safe_load(Path(__UpperCAmelCase ).read_text() ) , allow_extra_keys=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
293
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
293
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
1
"""simple docstring""" 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 _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] , model_result['ss'] ): lowerCAmelCase__ :Union[str, Any] = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Any = PyTorchBenchmark(__UpperCAmelCase ) lowerCAmelCase__ :int = 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 ): '''simple docstring''' lowerCAmelCase__ :Dict = 'sgugger/tiny-distilbert-classification' lowerCAmelCase__ :List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , only_pretrain_model=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = PyTorchBenchmark(__UpperCAmelCase ) lowerCAmelCase__ :int = 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 ): '''simple docstring''' lowerCAmelCase__ :Any = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , torchscript=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = 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 ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , fpaa=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = 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 ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :List[Any] = AutoConfig.from_pretrained(__UpperCAmelCase ) # set architectures equal to `None` lowerCAmelCase__ :str = None lowerCAmelCase__ :str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Any = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) lowerCAmelCase__ :Union[str, Any] = 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 ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = 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 ): '''simple docstring''' lowerCAmelCase__ :List[str] = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=__UpperCAmelCase , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) lowerCAmelCase__ :Dict = 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 ): '''simple docstring''' lowerCAmelCase__ :Any = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :Tuple = AutoConfig.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :List[Any] = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) lowerCAmelCase__ :List[str] = 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 ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = 'sshleifer/tinier_bart' lowerCAmelCase__ :Dict = AutoConfig.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Tuple = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) lowerCAmelCase__ :List[str] = 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 ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'sshleifer/tiny-gpt2' lowerCAmelCase__ :str = AutoConfig.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :List[str] = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) lowerCAmelCase__ :Any = 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 ): '''simple docstring''' lowerCAmelCase__ :Any = 'sshleifer/tinier_bart' lowerCAmelCase__ :Dict = AutoConfig.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) lowerCAmelCase__ :int = 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 ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ :Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , save_to_csv=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__UpperCAmelCase , 'inf_time.csv' ) , train_memory_csv_file=os.path.join(__UpperCAmelCase , 'train_mem.csv' ) , inference_memory_csv_file=os.path.join(__UpperCAmelCase , 'inf_mem.csv' ) , train_time_csv_file=os.path.join(__UpperCAmelCase , 'train_time.csv' ) , env_info_csv_file=os.path.join(__UpperCAmelCase , 'env.csv' ) , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :List[Any] = PyTorchBenchmark(__UpperCAmelCase ) benchmark.run() self.assertTrue(Path(os.path.join(__UpperCAmelCase , 'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , 'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , 'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , 'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , 'env.csv' ) ).exists() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(__UpperCAmelCase ): self.assertTrue(hasattr(__UpperCAmelCase , 'sequential' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'cumulative' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'current' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ :Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__UpperCAmelCase , 'log.txt' ) , log_print=__UpperCAmelCase , trace_memory_line_by_line=__UpperCAmelCase , multi_process=__UpperCAmelCase , ) lowerCAmelCase__ :List[Any] = PyTorchBenchmark(__UpperCAmelCase ) lowerCAmelCase__ :Dict = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , 'log.txt' ) ).exists() )
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: __A = None __A = logging.get_logger(__name__) __A = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __A = { """vocab_file""": { """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model""", """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model""", }, """tokenizer_file""": { """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json""", """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json""", }, } __A = { """xlnet-base-cased""": None, """xlnet-large-cased""": None, } __A = """▁""" # Segments (not really needed) __A = 0 __A = 1 __A = 2 __A = 3 __A = 4 class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Optional[Any] = VOCAB_FILES_NAMES __magic_name__ :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __magic_name__ :Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ :int = """left""" __magic_name__ :Optional[int] = XLNetTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase="<s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<sep>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="<cls>" , __UpperCAmelCase="<mask>" , __UpperCAmelCase=["<eop>", "<eod>"] , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token super().__init__( vocab_file=__UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = 3 lowerCAmelCase__ :Dict = do_lower_case lowerCAmelCase__ :Optional[Any] = remove_space lowerCAmelCase__ :Union[str, Any] = keep_accents lowerCAmelCase__ :Optional[Any] = vocab_file lowerCAmelCase__ :List[str] = False if not self.vocab_file else True def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [self.sep_token_id] lowerCAmelCase__ :Optional[int] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' lowerCAmelCase__ :str = [self.sep_token_id] lowerCAmelCase__ :List[str] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(__UpperCAmelCase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return lowerCAmelCase__ :List[str] = os.path.join( __UpperCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) return (out_vocab_file,)
293
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
1
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :Tuple = MobileBertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :Dict = MobileBertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint lowerCAmelCase__ :Any = load_tf_weights_in_mobilebert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
293
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
1
"""simple docstring""" from __future__ import annotations def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->dict[str, float]: """simple docstring""" if (voltage, current, resistance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance < 0: raise ValueError('Resistance cannot be negative' ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
293
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/config.json""", """umberto-commoncrawl-cased-v1""": ( """https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json""" ), """umberto-wikipedia-uncased-v1""": ( """https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json""" ), } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Dict = """camembert""" def __init__( self , __UpperCAmelCase=3_0_5_2_2 , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=5_1_2 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=2 , __UpperCAmelCase="absolute" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase__ :List[str] = vocab_size lowerCAmelCase__ :int = hidden_size lowerCAmelCase__ :Union[str, Any] = num_hidden_layers lowerCAmelCase__ :Any = num_attention_heads lowerCAmelCase__ :Optional[int] = hidden_act lowerCAmelCase__ :List[str] = intermediate_size lowerCAmelCase__ :List[str] = hidden_dropout_prob lowerCAmelCase__ :int = attention_probs_dropout_prob lowerCAmelCase__ :Dict = max_position_embeddings lowerCAmelCase__ :List[Any] = type_vocab_size lowerCAmelCase__ :Optional[int] = initializer_range lowerCAmelCase__ :Tuple = layer_norm_eps lowerCAmelCase__ :int = position_embedding_type lowerCAmelCase__ :Tuple = use_cache lowerCAmelCase__ :Optional[Any] = classifier_dropout class _lowerCAmelCase ( a ): """simple docstring""" @property def snake_case ( self ): '''simple docstring''' if self.task == "multiple-choice": lowerCAmelCase__ :Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowerCAmelCase__ :Optional[int] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
293
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right __A = 25_0004 __A = 25_0020 @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :Optional[int] = MBartaaTokenizer __magic_name__ :List[Any] = MBartaaTokenizerFast __magic_name__ :str = True __magic_name__ :int = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :str = MBartaaTokenizer(__UpperCAmelCase , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = '<s>' lowerCAmelCase__ :Optional[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_5_4 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_5_4 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = MBartaaTokenizer(__UpperCAmelCase , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :List[str] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , ) lowerCAmelCase__ :List[Any] = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :str = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = {'input_ids': [[2_5_0_0_0_4, 1_1_0_6_2, 8_2_7_7_2, 7, 1_5, 8_2_7_7_2, 5_3_8, 5_1_5_2_9, 2_3_7, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 2_1_5_1_7_5, 1_3_1_4, 1_3_6, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 5_6_3_5_9, 4_2, 1_2_2_0_0_9, 9, 1_6_4_6_6, 1_6, 8_7_3_4_4, 4_5_3_7, 9, 4_7_1_7, 7_8_3_8_1, 6, 1_5_9_9_5_8, 7, 1_5, 2_4_4_8_0, 6_1_8, 4, 5_2_7, 2_2_6_9_3, 5_4_2_8, 4, 2_7_7_7, 2_4_4_8_0, 9_8_7_4, 4, 4_3_5_2_3, 5_9_4, 4, 8_0_3, 1_8_3_9_2, 3_3_1_8_9, 1_8, 4, 4_3_5_2_3, 2_4_4_4_7, 1_2_3_9_9, 1_0_0, 2_4_9_5_5, 8_3_6_5_8, 9_6_2_6, 1_4_4_0_5_7, 1_5, 8_3_9, 2_2_3_3_5, 1_6, 1_3_6, 2_4_9_5_5, 8_3_6_5_8, 8_3_4_7_9, 1_5, 3_9_1_0_2, 7_2_4, 1_6, 6_7_8, 6_4_5, 2_7_8_9, 1_3_2_8, 4_5_8_9, 4_2, 1_2_2_0_0_9, 1_1_5_7_7_4, 2_3, 8_0_5, 1_3_2_8, 4_6_8_7_6, 7, 1_3_6, 5_3_8_9_4, 1_9_4_0, 4_2_2_2_7, 4_1_1_5_9, 1_7_7_2_1, 8_2_3, 4_2_5, 4, 2_7_5_1_2, 9_8_7_2_2, 2_0_6, 1_3_6, 5_5_3_1, 4_9_7_0, 9_1_9, 1_7_3_3_6, 5, 2], [2_5_0_0_0_4, 2_0_0_8_0, 6_1_8, 8_3, 8_2_7_7_5, 4_7, 4_7_9, 9, 1_5_1_7, 7_3, 5_3_8_9_4, 3_3_3, 8_0_5_8_1, 1_1_0_1_1_7, 1_8_8_1_1, 5_2_5_6, 1_2_9_5, 5_1, 1_5_2_5_2_6, 2_9_7, 7_9_8_6, 3_9_0, 1_2_4_4_1_6, 5_3_8, 3_5_4_3_1, 2_1_4, 9_8, 1_5_0_4_4, 2_5_7_3_7, 1_3_6, 7_1_0_8, 4_3_7_0_1, 2_3, 7_5_6, 1_3_5_3_5_5, 7, 5, 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], [2_5_0_0_0_4, 5_8_1, 6_3_7_7_3, 1_1_9_4_5_5, 6, 1_4_7_7_9_7, 8_8_2_0_3, 7, 6_4_5, 7_0, 2_1, 3_2_8_5, 1_0_2_6_9, 5, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/mbart-large-50' , revision='d3913889c59cd5c9e456b269c376325eabad57e2' , ) def snake_case ( self ): '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCAmelCase__ :Optional[Any] = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart50', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): lowerCAmelCase__ :Union[str, Any] = self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self.tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase__ :List[str] = tempfile.mkdtemp() lowerCAmelCase__ :int = tokenizer_r.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer_p.save_pretrained(__UpperCAmelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) lowerCAmelCase__ :List[Any] = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(__UpperCAmelCase , __UpperCAmelCase ) # Checks everything loads correctly in the same way lowerCAmelCase__ :Any = tokenizer_r.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__UpperCAmelCase ) # Save tokenizer rust, legacy_format=True lowerCAmelCase__ :Any = tempfile.mkdtemp() lowerCAmelCase__ :str = tokenizer_r.save_pretrained(__UpperCAmelCase , legacy_format=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer_p.save_pretrained(__UpperCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(__UpperCAmelCase , __UpperCAmelCase ) # Checks everything loads correctly in the same way lowerCAmelCase__ :int = tokenizer_r.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :int = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) shutil.rmtree(__UpperCAmelCase ) # Save tokenizer rust, legacy_format=False lowerCAmelCase__ :str = tempfile.mkdtemp() lowerCAmelCase__ :str = tokenizer_r.save_pretrained(__UpperCAmelCase , legacy_format=__UpperCAmelCase ) lowerCAmelCase__ :List[str] = tokenizer_p.save_pretrained(__UpperCAmelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCAmelCase__ :Optional[int] = tokenizer_r.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) shutil.rmtree(__UpperCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = """facebook/mbart-large-50-one-to-many-mmt""" __magic_name__ :Dict = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] __magic_name__ :str = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei""" """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor""" """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] __magic_name__ :Union[str, Any] = [EN_CODE, 8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2] @classmethod def snake_case ( cls ): '''simple docstring''' lowerCAmelCase__ :MBartaaTokenizer = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) lowerCAmelCase__ :List[Any] = 1 return cls def snake_case ( self ): '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 2_5_0_0_2_0 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'] , 2_5_0_0_3_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.assertIn(__UpperCAmelCase , self.tokenizer.all_special_ids ) lowerCAmelCase__ :Dict = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] lowerCAmelCase__ :str = self.tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = ['this is gunna be a long sentence ' * 2_0] assert isinstance(src_text[0] , __UpperCAmelCase ) lowerCAmelCase__ :Dict = 1_0 lowerCAmelCase__ :List[str] = self.tokenizer(__UpperCAmelCase , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase ).input_ids[0] self.assertEqual(ids[0] , __UpperCAmelCase ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [2_5_0_0_5_3, 2_5_0_0_0_1] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tempfile.mkdtemp() lowerCAmelCase__ :List[str] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = MBartaaTokenizer.from_pretrained(__UpperCAmelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __UpperCAmelCase ) @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__UpperCAmelCase , return_tensors='pt' ) lowerCAmelCase__ :Dict = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) lowerCAmelCase__ :List[Any] = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) lowerCAmelCase__ :Dict = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __UpperCAmelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = self.tokenizer(self.src_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=3 , return_tensors='pt' ) lowerCAmelCase__ :Optional[Any] = self.tokenizer( text_target=self.tgt_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=1_0 , return_tensors='pt' ) lowerCAmelCase__ :str = targets['input_ids'] lowerCAmelCase__ :Union[str, Any] = shift_tokens_right(__UpperCAmelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { # en_XX, A, test, EOS 'input_ids': [[2_5_0_0_0_4, 6_2, 3_0_3_4, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 2_5_0_0_0_1, } , )
293
"""simple docstring""" 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 _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = 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(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
1
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule __A = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
1
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :int = '' for i in table: res += inp[i - 1] return res def __A (_SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" return data[1:] + data[0] def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" lowerCAmelCase__ :Dict = '' for i in range(len(_SCREAMING_SNAKE_CASE ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = int('0b' + data[0] + data[-1] , 2 ) lowerCAmelCase__ :Any = int('0b' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str: """simple docstring""" lowerCAmelCase__ :str = message[:4] lowerCAmelCase__ :str = message[4:] lowerCAmelCase__ :List[Any] = apply_table(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = xor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = apply_sbox(_SCREAMING_SNAKE_CASE , temp[:4] ) # noqa: E741 lowerCAmelCase__ :Dict = apply_sbox(_SCREAMING_SNAKE_CASE , temp[4:] ) lowerCAmelCase__ :Dict = '0' * (2 - len(_SCREAMING_SNAKE_CASE )) + l # noqa: E741 lowerCAmelCase__ :Union[str, Any] = '0' * (2 - len(_SCREAMING_SNAKE_CASE )) + r lowerCAmelCase__ :List[str] = apply_table(l + r , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :int = xor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return temp + right if __name__ == "__main__": __A = input("""Enter 10 bit key: """) __A = input("""Enter 8 bit message: """) __A = [6, 3, 7, 4, 8, 5, 10, 9] __A = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] __A = [2, 4, 3, 1] __A = [2, 6, 3, 1, 4, 8, 5, 7] __A = [4, 1, 3, 5, 7, 2, 8, 6] __A = [4, 1, 2, 3, 2, 3, 4, 1] __A = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] __A = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation __A = apply_table(key, paa_table) __A = temp[:5] __A = temp[5:] __A = left_shift(left) __A = left_shift(right) __A = apply_table(left + right, pa_table) __A = left_shift(left) __A = left_shift(right) __A = left_shift(left) __A = left_shift(right) __A = apply_table(left + right, pa_table) # encryption __A = apply_table(message, IP) __A = function(expansion, sa, sa, keya, temp) __A = temp[4:] + temp[:4] __A = function(expansion, sa, sa, keya, temp) __A = apply_table(temp, IP_inv) print("""Cipher text is:""", CT) # decryption __A = apply_table(CT, IP) __A = function(expansion, sa, sa, keya, temp) __A = temp[4:] + temp[:4] __A = function(expansion, sa, sa, keya, temp) __A = apply_table(temp, IP_inv) print("""Plain text after decypting is:""", PT)
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy __A = logging.get_logger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = feature_size lowerCAmelCase__ :int = sampling_rate lowerCAmelCase__ :List[Any] = padding_value lowerCAmelCase__ :Union[str, Any] = kwargs.pop('padding_side' , 'right' ) lowerCAmelCase__ :List[str] = kwargs.pop('return_attention_mask' , __UpperCAmelCase ) super().__init__(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , ): '''simple docstring''' if isinstance(__UpperCAmelCase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): lowerCAmelCase__ :Any = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' F" to this method that includes {self.model_input_names[0]}, but you provided" F" {list(processed_features.keys() )}" ) lowerCAmelCase__ :List[Any] = processed_features[self.model_input_names[0]] lowerCAmelCase__ :Union[str, Any] = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(__UpperCAmelCase ) == 0: if return_attention_mask: lowerCAmelCase__ :Optional[Any] = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch lowerCAmelCase__ :Tuple = required_input[0] if isinstance(__UpperCAmelCase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. lowerCAmelCase__ :int = 0 while len(required_input[index] ) == 0: index += 1 if index < len(__UpperCAmelCase ): lowerCAmelCase__ :int = required_input[index][0] if return_tensors is None: if is_tf_tensor(__UpperCAmelCase ): lowerCAmelCase__ :str = 'tf' elif is_torch_tensor(__UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = 'pt' elif isinstance(__UpperCAmelCase , (int, float, list, tuple, np.ndarray) ): lowerCAmelCase__ :Union[str, Any] = 'np' else: raise ValueError( F"type of {first_element} unknown: {type(__UpperCAmelCase )}. " 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): lowerCAmelCase__ :Optional[Any] = to_numpy(__UpperCAmelCase ) else: lowerCAmelCase__ :List[Any] = [to_numpy(__UpperCAmelCase ) for v in value] # Convert padding_strategy in PaddingStrategy lowerCAmelCase__ :List[Any] = self._get_padding_strategies(padding=__UpperCAmelCase , max_length=__UpperCAmelCase ) lowerCAmelCase__ :Dict = processed_features[self.model_input_names[0]] lowerCAmelCase__ :List[str] = len(__UpperCAmelCase ) if not all(len(__UpperCAmelCase ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) lowerCAmelCase__ :Any = [] for i in range(__UpperCAmelCase ): lowerCAmelCase__ :Dict = {k: v[i] for k, v in processed_features.items()} # truncation lowerCAmelCase__ :str = self._truncate( __UpperCAmelCase , max_length=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , truncation=__UpperCAmelCase , ) truncated_inputs.append(__UpperCAmelCase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length lowerCAmelCase__ :Dict = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) lowerCAmelCase__ :str = PaddingStrategy.MAX_LENGTH lowerCAmelCase__ :Tuple = {} for i in range(__UpperCAmelCase ): # padding lowerCAmelCase__ :List[str] = self._pad( truncated_inputs[i] , max_length=__UpperCAmelCase , padding_strategy=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , ) for key, value in outputs.items(): if key not in batch_outputs: lowerCAmelCase__ :Tuple = [] if value.dtype is np.dtype(np.floataa ): lowerCAmelCase__ :Optional[Any] = value.astype(np.floataa ) batch_outputs[key].append(__UpperCAmelCase ) return BatchFeature(__UpperCAmelCase , tensor_type=__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = PaddingStrategy.DO_NOT_PAD , __UpperCAmelCase = None , __UpperCAmelCase = None , ): '''simple docstring''' lowerCAmelCase__ :Dict = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: lowerCAmelCase__ :Optional[int] = len(__UpperCAmelCase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): lowerCAmelCase__ :List[Any] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of lowerCAmelCase__ :Union[str, Any] = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(__UpperCAmelCase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: lowerCAmelCase__ :str = np.ones(len(__UpperCAmelCase ) , dtype=np.intaa ) if needs_to_be_padded: lowerCAmelCase__ :Dict = max_length - len(__UpperCAmelCase ) if self.padding_side == "right": if return_attention_mask: lowerCAmelCase__ :List[str] = np.pad( processed_features['attention_mask'] , (0, difference) ) lowerCAmelCase__ :Union[str, Any] = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) lowerCAmelCase__ :Optional[int] = np.pad( __UpperCAmelCase , __UpperCAmelCase , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: lowerCAmelCase__ :List[str] = np.pad( processed_features['attention_mask'] , (difference, 0) ) lowerCAmelCase__ :List[str] = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) lowerCAmelCase__ :List[Any] = np.pad( __UpperCAmelCase , __UpperCAmelCase , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , ): '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) lowerCAmelCase__ :Tuple = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): lowerCAmelCase__ :Dict = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of lowerCAmelCase__ :Optional[Any] = len(__UpperCAmelCase ) > max_length if needs_to_be_truncated: lowerCAmelCase__ :Dict = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: lowerCAmelCase__ :Optional[int] = processed_features['attention_mask'][:max_length] return processed_features def snake_case ( self , __UpperCAmelCase=False , __UpperCAmelCase=None ): '''simple docstring''' if padding is not False: if padding is True: lowerCAmelCase__ :Union[str, Any] = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Tuple = PaddingStrategy(__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = padding else: lowerCAmelCase__ :List[str] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
293
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = """rwkv""" __magic_name__ :int = {"""max_position_embeddings""": """context_length"""} def __init__( self , __UpperCAmelCase=5_0_2_7_7 , __UpperCAmelCase=1_0_2_4 , __UpperCAmelCase=4_0_9_6 , __UpperCAmelCase=3_2 , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=1E-5 , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=6 , __UpperCAmelCase=False , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = vocab_size lowerCAmelCase__ :List[Any] = context_length lowerCAmelCase__ :List[str] = hidden_size lowerCAmelCase__ :Tuple = num_hidden_layers lowerCAmelCase__ :List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size lowerCAmelCase__ :Dict = intermediate_size if intermediate_size is not None else 4 * hidden_size lowerCAmelCase__ :Union[str, Any] = layer_norm_epsilon lowerCAmelCase__ :int = rescale_every lowerCAmelCase__ :Dict = use_cache lowerCAmelCase__ :Union[str, Any] = bos_token_id lowerCAmelCase__ :List[str] = eos_token_id super().__init__( tie_word_embeddings=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase )
293
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
1
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") __A = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") __A = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = CamembertTokenizer __magic_name__ :int = CamembertTokenizerFast __magic_name__ :Optional[Any] = True __magic_name__ :Any = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :Tuple = CamembertTokenizer(__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_4 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = CamembertTokenizer(__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :Dict = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) lowerCAmelCase__ :Dict = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :List[str] = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Dict = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :str = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) lowerCAmelCase__ :Tuple = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Union[str, Any] = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :str = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Dict = self.get_rust_tokenizer() lowerCAmelCase__ :Any = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :int = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = {'input_ids': [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 9, 6]], '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, 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, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. lowerCAmelCase__ :Any = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=__UpperCAmelCase , )
293
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
1
"""simple docstring""" import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :Union[str, Any] = """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline""" def snake_case ( self , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = np.random.RandomState(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = self.get_dummy_inputs() lowerCAmelCase__ :Union[str, Any] = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :str = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) lowerCAmelCase__ :Any = np.array([0.6_50_72, 0.5_84_92, 0.4_82_19, 0.5_55_21, 0.5_31_80, 0.5_59_39, 0.5_06_97, 0.3_98_00, 0.4_64_55] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) lowerCAmelCase__ :Dict = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.get_dummy_inputs() lowerCAmelCase__ :Tuple = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) lowerCAmelCase__ :List[Any] = np.array([0.6_58_63, 0.5_94_25, 0.4_93_26, 0.5_63_13, 0.5_38_75, 0.5_66_27, 0.5_10_65, 0.3_97_77, 0.4_63_30] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) lowerCAmelCase__ :Any = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :int = self.get_dummy_inputs() lowerCAmelCase__ :List[Any] = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) lowerCAmelCase__ :Optional[Any] = np.array([0.5_37_55, 0.6_07_86, 0.4_74_02, 0.4_94_88, 0.5_18_69, 0.4_98_19, 0.4_79_85, 0.3_89_57, 0.4_42_79] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) lowerCAmelCase__ :str = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :List[str] = self.get_dummy_inputs() lowerCAmelCase__ :List[Any] = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) lowerCAmelCase__ :Union[str, Any] = np.array([0.5_37_55, 0.6_07_86, 0.4_74_02, 0.4_94_88, 0.5_18_69, 0.4_98_19, 0.4_79_85, 0.3_89_57, 0.4_42_79] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) lowerCAmelCase__ :Optional[int] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_dummy_inputs() lowerCAmelCase__ :Union[str, Any] = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) lowerCAmelCase__ :Tuple = np.array([0.5_38_17, 0.6_08_12, 0.4_73_84, 0.4_95_30, 0.5_18_94, 0.4_98_14, 0.4_79_84, 0.3_89_58, 0.4_42_71] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) lowerCAmelCase__ :int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.get_dummy_inputs() lowerCAmelCase__ :Dict = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) lowerCAmelCase__ :List[Any] = np.array([0.5_38_95, 0.6_08_08, 0.4_79_33, 0.4_96_08, 0.5_18_86, 0.4_99_50, 0.4_80_53, 0.3_89_57, 0.4_42_00] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs() lowerCAmelCase__ :List[str] = 3 * [inputs['prompt']] # forward lowerCAmelCase__ :Dict = pipe(**__UpperCAmelCase ) lowerCAmelCase__ :str = output.images[0, -3:, -3:, -1] lowerCAmelCase__ :List[Any] = self.get_dummy_inputs() lowerCAmelCase__ :Optional[Any] = 3 * [inputs.pop('prompt' )] lowerCAmelCase__ :Tuple = pipe.tokenizer( __UpperCAmelCase , padding='max_length' , max_length=pipe.tokenizer.model_max_length , truncation=__UpperCAmelCase , return_tensors='np' , ) lowerCAmelCase__ :Optional[Any] = text_inputs['input_ids'] lowerCAmelCase__ :Optional[Any] = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] lowerCAmelCase__ :Tuple = prompt_embeds # forward lowerCAmelCase__ :Any = pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[str] = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs() lowerCAmelCase__ :Optional[Any] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Optional[Any] = negative_prompt lowerCAmelCase__ :List[Any] = 3 * [inputs['prompt']] # forward lowerCAmelCase__ :Optional[Any] = pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] lowerCAmelCase__ :str = self.get_dummy_inputs() lowerCAmelCase__ :int = 3 * [inputs.pop('prompt' )] lowerCAmelCase__ :Any = [] for p in [prompt, negative_prompt]: lowerCAmelCase__ :Tuple = pipe.tokenizer( __UpperCAmelCase , padding='max_length' , max_length=pipe.tokenizer.model_max_length , truncation=__UpperCAmelCase , return_tensors='np' , ) lowerCAmelCase__ :Any = text_inputs['input_ids'] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) lowerCAmelCase__ , lowerCAmelCase__ :str = embeds # forward lowerCAmelCase__ :str = pipe(**__UpperCAmelCase ) lowerCAmelCase__ :Dict = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @nightly @require_onnxruntime @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @property def snake_case ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = ort.SessionOptions() lowerCAmelCase__ :str = False return options def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = OnnxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = 'A painting of a squirrel eating a burger' np.random.seed(0 ) lowerCAmelCase__ :Optional[Any] = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=1_0 , output_type='np' ) lowerCAmelCase__ :Optional[Any] = output.images lowerCAmelCase__ :Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :Tuple = np.array([0.04_52, 0.03_90, 0.00_87, 0.03_50, 0.06_17, 0.03_64, 0.05_44, 0.05_23, 0.07_20] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = DDIMScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) lowerCAmelCase__ :List[str] = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = 'open neural network exchange' lowerCAmelCase__ :Any = np.random.RandomState(0 ) lowerCAmelCase__ :Optional[int] = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=1_0 , generator=__UpperCAmelCase , output_type='np' ) lowerCAmelCase__ :int = output.images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :Dict = np.array([0.28_67, 0.19_74, 0.14_81, 0.72_94, 0.72_51, 0.66_67, 0.41_94, 0.56_42, 0.64_86] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) lowerCAmelCase__ :Tuple = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = 'open neural network exchange' lowerCAmelCase__ :str = np.random.RandomState(0 ) lowerCAmelCase__ :Optional[Any] = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=1_0 , generator=__UpperCAmelCase , output_type='np' ) lowerCAmelCase__ :Any = output.images lowerCAmelCase__ :Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.23_06, 0.19_59, 0.15_93, 0.65_49, 0.63_94, 0.54_08, 0.50_65, 0.60_10, 0.61_61] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 0 def test_callback_fn(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> None: lowerCAmelCase__ :Optional[int] = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 6_4, 6_4) lowerCAmelCase__ :Optional[Any] = latents[0, -3:, -3:, -1] lowerCAmelCase__ :Optional[int] = np.array( [-0.67_72, -0.38_35, -1.24_56, 0.19_05, -1.09_74, 0.69_67, -1.93_53, 0.01_78, 1.01_67] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3 elif step == 5: assert latents.shape == (1, 4, 6_4, 6_4) lowerCAmelCase__ :List[str] = latents[0, -3:, -3:, -1] lowerCAmelCase__ :Union[str, Any] = np.array( [-0.33_51, 0.22_41, -0.18_37, -0.23_25, -0.65_77, 0.33_93, -0.02_41, 0.58_99, 1.38_75] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3 lowerCAmelCase__ :Any = False lowerCAmelCase__ :Tuple = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = 'Andromeda galaxy in a bottle' lowerCAmelCase__ :Tuple = np.random.RandomState(0 ) pipe( prompt=__UpperCAmelCase , num_inference_steps=5 , guidance_scale=7.5 , generator=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert pipe.safety_checker is None lowerCAmelCase__ :int = 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(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = OnnxStableDiffusionPipeline.from_pretrained(__UpperCAmelCase ) # sanity check that the pipeline still works assert pipe.safety_checker is None lowerCAmelCase__ :Union[str, Any] = pipe('example prompt' , num_inference_steps=2 ).images[0] assert image is not None
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=1_4 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=9_9 , __UpperCAmelCase=3_2 , __UpperCAmelCase=4 , __UpperCAmelCase=4 , __UpperCAmelCase=4 , __UpperCAmelCase=3_7 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=5_1_2 , __UpperCAmelCase=0.02 , ): '''simple docstring''' lowerCAmelCase__ :str = parent lowerCAmelCase__ :int = batch_size lowerCAmelCase__ :Dict = seq_length lowerCAmelCase__ :Union[str, Any] = is_training lowerCAmelCase__ :int = use_input_mask lowerCAmelCase__ :Tuple = use_token_type_ids lowerCAmelCase__ :Optional[int] = use_labels lowerCAmelCase__ :Dict = vocab_size lowerCAmelCase__ :str = hidden_size lowerCAmelCase__ :Union[str, Any] = rotary_dim lowerCAmelCase__ :Dict = num_hidden_layers lowerCAmelCase__ :Optional[int] = num_attention_heads lowerCAmelCase__ :Tuple = intermediate_size lowerCAmelCase__ :Dict = hidden_act lowerCAmelCase__ :Tuple = hidden_dropout_prob lowerCAmelCase__ :Dict = attention_probs_dropout_prob lowerCAmelCase__ :Any = max_position_embeddings lowerCAmelCase__ :str = initializer_range lowerCAmelCase__ :str = None lowerCAmelCase__ :List[Any] = vocab_size - 1 lowerCAmelCase__ :List[str] = vocab_size - 1 lowerCAmelCase__ :str = vocab_size - 1 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ :List[str] = None if self.use_input_mask: lowerCAmelCase__ :Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ :List[str] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=__UpperCAmelCase , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = config_and_inputs lowerCAmelCase__ :Union[str, Any] = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 2_0 lowerCAmelCase__ :Union[str, Any] = model_class_name(__UpperCAmelCase ) lowerCAmelCase__ :str = model.init_cache(input_ids.shape[0] , __UpperCAmelCase ) lowerCAmelCase__ :str = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) lowerCAmelCase__ :List[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowerCAmelCase__ :Tuple = model( input_ids[:, :-1] , attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , position_ids=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[int] = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) lowerCAmelCase__ :List[str] = model( input_ids[:, -1:] , attention_mask=__UpperCAmelCase , past_key_values=outputs_cache.past_key_values , position_ids=__UpperCAmelCase , ) lowerCAmelCase__ :List[str] = model(__UpperCAmelCase ) lowerCAmelCase__ :str = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"Max diff is {diff}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = 2_0 lowerCAmelCase__ :Any = model_class_name(__UpperCAmelCase ) lowerCAmelCase__ :Any = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) lowerCAmelCase__ :Any = model.init_cache(input_ids.shape[0] , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowerCAmelCase__ :Union[str, Any] = model( input_ids[:, :-1] , attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , position_ids=__UpperCAmelCase , ) lowerCAmelCase__ :Tuple = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) lowerCAmelCase__ :List[Any] = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=__UpperCAmelCase , position_ids=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[int] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"Max diff is {diff}" ) @require_flax class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Any = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () __magic_name__ :Union[str, Any] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = FlaxGPTJModelTester(self ) def snake_case ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) @tooslow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) lowerCAmelCase__ :Dict = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=__UpperCAmelCase , truncation=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) lowerCAmelCase__ :Dict = False lowerCAmelCase__ :Dict = model.config.eos_token_id lowerCAmelCase__ :Dict = jax.jit(model.generate ) lowerCAmelCase__ :Any = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences lowerCAmelCase__ :Optional[Any] = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @is_pt_flax_cross_test def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowerCAmelCase__ :Tuple = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCAmelCase__ :Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCAmelCase__ :int = getattr(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ :str = pt_inputs['input_ids'].shape lowerCAmelCase__ :Tuple = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__UpperCAmelCase ): lowerCAmelCase__ :Tuple = 0 lowerCAmelCase__ :str = 1 lowerCAmelCase__ :int = 0 lowerCAmelCase__ :Dict = 1 lowerCAmelCase__ :Union[str, Any] = pt_model_class(__UpperCAmelCase ).eval() lowerCAmelCase__ :List[Any] = model_class(__UpperCAmelCase , dtype=jnp.floataa ) lowerCAmelCase__ :Optional[int] = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , __UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = fx_state with torch.no_grad(): lowerCAmelCase__ :Optional[int] = pt_model(**__UpperCAmelCase ).to_tuple() lowerCAmelCase__ :Union[str, Any] = fx_model(**__UpperCAmelCase ).to_tuple() self.assertEqual(len(__UpperCAmelCase ) , len(__UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = model_class.from_pretrained(__UpperCAmelCase , from_pt=__UpperCAmelCase ) lowerCAmelCase__ :Any = fx_model_loaded(**__UpperCAmelCase ).to_tuple() self.assertEqual( len(__UpperCAmelCase ) , len(__UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowerCAmelCase__ :Any = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCAmelCase__ :str = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCAmelCase__ :Optional[int] = getattr(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = pt_model_class(__UpperCAmelCase ).eval() lowerCAmelCase__ :Union[str, Any] = model_class(__UpperCAmelCase , dtype=jnp.floataa ) lowerCAmelCase__ :str = load_flax_weights_in_pytorch_model(__UpperCAmelCase , fx_model.params ) lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = pt_inputs['input_ids'].shape lowerCAmelCase__ :Optional[Any] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__UpperCAmelCase ): lowerCAmelCase__ :Any = 0 lowerCAmelCase__ :Tuple = 1 lowerCAmelCase__ :Dict = 0 lowerCAmelCase__ :Optional[int] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): lowerCAmelCase__ :str = pt_model(**__UpperCAmelCase ).to_tuple() lowerCAmelCase__ :int = fx_model(**__UpperCAmelCase ).to_tuple() self.assertEqual(len(__UpperCAmelCase ) , len(__UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pt_model_class.from_pretrained(__UpperCAmelCase , from_flax=__UpperCAmelCase ) with torch.no_grad(): lowerCAmelCase__ :List[Any] = pt_model_loaded(**__UpperCAmelCase ).to_tuple() self.assertEqual( len(__UpperCAmelCase ) , len(__UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def snake_case ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: lowerCAmelCase__ :Optional[int] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) lowerCAmelCase__ :Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(__UpperCAmelCase )
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available 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 torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=1_3 , __UpperCAmelCase=2 , __UpperCAmelCase=2_4 , __UpperCAmelCase=1_6 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=3_2 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=3_7 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=1_0 , __UpperCAmelCase=0.02 , __UpperCAmelCase=None , __UpperCAmelCase=2 , __UpperCAmelCase=2 , ): '''simple docstring''' lowerCAmelCase__ :List[str] = parent lowerCAmelCase__ :Any = batch_size lowerCAmelCase__ :Optional[Any] = patch_size lowerCAmelCase__ :Optional[int] = max_length lowerCAmelCase__ :str = num_mel_bins lowerCAmelCase__ :Union[str, Any] = is_training lowerCAmelCase__ :Dict = use_labels lowerCAmelCase__ :Optional[Any] = hidden_size lowerCAmelCase__ :List[str] = num_hidden_layers lowerCAmelCase__ :List[Any] = num_attention_heads lowerCAmelCase__ :Tuple = intermediate_size lowerCAmelCase__ :Tuple = hidden_act lowerCAmelCase__ :Union[str, Any] = hidden_dropout_prob lowerCAmelCase__ :Any = attention_probs_dropout_prob lowerCAmelCase__ :Any = type_sequence_label_size lowerCAmelCase__ :Optional[Any] = initializer_range lowerCAmelCase__ :Optional[Any] = scope lowerCAmelCase__ :Tuple = frequency_stride lowerCAmelCase__ :Optional[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) lowerCAmelCase__ :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 lowerCAmelCase__ :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 lowerCAmelCase__ :Tuple = frequency_out_dimension * time_out_dimension lowerCAmelCase__ :Tuple = num_patches + 2 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) lowerCAmelCase__ :Optional[Any] = None if self.use_labels: lowerCAmelCase__ :List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ :Dict = self.get_config() return config, input_values, labels def snake_case ( self ): '''simple docstring''' return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , 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=__UpperCAmelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = ASTModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ :Dict = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :int = config_and_inputs lowerCAmelCase__ :Optional[Any] = {'input_values': input_values} return config, inputs_dict @require_torch class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) __magic_name__ :Tuple = ( {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel} if is_torch_available() else {} ) __magic_name__ :int = False __magic_name__ :Tuple = False __magic_name__ :Any = False __magic_name__ :List[Any] = False def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = ASTModelTester(self ) lowerCAmelCase__ :List[str] = ConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase , hidden_size=3_7 ) def snake_case ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='AST does not use inputs_embeds' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :str = model_class(__UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ :Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCAmelCase , nn.Linear ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :Optional[Any] = model_class(__UpperCAmelCase ) lowerCAmelCase__ :Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ :Tuple = [*signature.parameters.keys()] lowerCAmelCase__ :Optional[Any] = ['input_values'] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ :Union[str, Any] = ASTModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def __A () ->Optional[int]: """simple docstring""" lowerCAmelCase__ :int = hf_hub_download( repo_id='nielsr/audio-spectogram-transformer-checkpoint' , filename='sample_audio.flac' , repo_type='dataset' ) lowerCAmelCase__ , lowerCAmelCase__ :List[str] = torchaudio.load(_SCREAMING_SNAKE_CASE ) return audio, sampling_rate @require_torch @require_torchaudio class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case ( self ): '''simple docstring''' return ( ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' ) if is_torchaudio_available() else None ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.default_feature_extractor lowerCAmelCase__ :Optional[Any] = ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' ).to(__UpperCAmelCase ) lowerCAmelCase__ :int = self.default_feature_extractor lowerCAmelCase__ , lowerCAmelCase__ :int = prepare_audio() lowerCAmelCase__ :Optional[Any] = audio.squeeze().numpy() lowerCAmelCase__ :Any = feature_extractor(__UpperCAmelCase , sampling_rate=__UpperCAmelCase , return_tensors='pt' ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): lowerCAmelCase__ :Tuple = model(**__UpperCAmelCase ) # verify the logits lowerCAmelCase__ :Any = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCAmelCase , atol=1E-4 ) )
293
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( 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 _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" 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 = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = 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' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
1
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = data lowerCAmelCase__ :List[Any] = [0x67_45_23_01, 0xef_cd_ab_89, 0x98_ba_dc_fe, 0x10_32_54_76, 0xc3_d2_e1_f0] @staticmethod def snake_case ( __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' return ((n << b) | (n >> (3_2 - b))) & 0xff_ff_ff_ff def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = B'\x80' + B'\x00' * (6_3 - (len(self.data ) + 8) % 6_4) lowerCAmelCase__ :Any = self.data + padding + struct.pack('>Q' , 8 * len(self.data ) ) return padded_data def snake_case ( self ): '''simple docstring''' return [ self.padded_data[i : i + 6_4] for i in range(0 , len(self.padded_data ) , 6_4 ) ] def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = list(struct.unpack('>16L' , __UpperCAmelCase ) ) + [0] * 6_4 for i in range(1_6 , 8_0 ): lowerCAmelCase__ :Any = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 1_4] ^ w[i - 1_6]) , 1 ) return w def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.padding() lowerCAmelCase__ :List[str] = self.split_blocks() for block in self.blocks: lowerCAmelCase__ :int = self.expand_block(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.h for i in range(0 , 8_0 ): if 0 <= i < 2_0: lowerCAmelCase__ :Tuple = (b & c) | ((~b) & d) lowerCAmelCase__ :Any = 0x5a_82_79_99 elif 2_0 <= i < 4_0: lowerCAmelCase__ :str = b ^ c ^ d lowerCAmelCase__ :Dict = 0x6e_d9_eb_a1 elif 4_0 <= i < 6_0: lowerCAmelCase__ :Optional[int] = (b & c) | (b & d) | (c & d) lowerCAmelCase__ :str = 0x8f_1b_bc_dc elif 6_0 <= i < 8_0: lowerCAmelCase__ :Optional[Any] = b ^ c ^ d lowerCAmelCase__ :Any = 0xca_62_c1_d6 lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = ( self.rotate(__UpperCAmelCase , 5 ) + f + e + k + expanded_block[i] & 0xff_ff_ff_ff, a, self.rotate(__UpperCAmelCase , 3_0 ), c, d, ) lowerCAmelCase__ :Dict = ( self.h[0] + a & 0xff_ff_ff_ff, self.h[1] + b & 0xff_ff_ff_ff, self.h[2] + c & 0xff_ff_ff_ff, self.h[3] + d & 0xff_ff_ff_ff, self.h[4] + e & 0xff_ff_ff_ff, ) return ("{:08x}" * 5).format(*self.h ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Dict = B'Test String' assert SHAaHash(_SCREAMING_SNAKE_CASE ).final_hash() == hashlib.shaa(_SCREAMING_SNAKE_CASE ).hexdigest() # noqa: S324 def __A () ->Dict: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = argparse.ArgumentParser(description='Process some strings or files' ) parser.add_argument( '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument('--file' , dest='input_file' , help='Hash contents of a file' ) lowerCAmelCase__ :Dict = parser.parse_args() lowerCAmelCase__ :Optional[int] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: lowerCAmelCase__ :List[Any] = f.read() else: lowerCAmelCase__ :int = bytes(_SCREAMING_SNAKE_CASE , 'utf-8' ) print(SHAaHash(_SCREAMING_SNAKE_CASE ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
293
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
1
"""simple docstring""" import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger __A = get_logger(__name__) class _lowerCAmelCase ( enum.Enum ): """simple docstring""" __magic_name__ :Union[str, Any] = """all_checks""" __magic_name__ :Tuple = """basic_checks""" __magic_name__ :int = """no_checks""" class _lowerCAmelCase ( a ): """simple docstring""" class _lowerCAmelCase ( a ): """simple docstring""" class _lowerCAmelCase ( a ): """simple docstring""" class _lowerCAmelCase ( a ): """simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) ->Optional[Any]: """simple docstring""" if expected_checksums is None: logger.info('Unable to verify checksums.' ) return if len(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) ) if len(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedDownloadedFile(str(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) ) lowerCAmelCase__ :Union[str, Any] = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] lowerCAmelCase__ :int = ' for ' + verification_name if verification_name is not None else '' if len(_SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingChecksumError( F"Checksums didn't match{for_verification_name}:\n" F"{bad_urls}\n" 'Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error' ) logger.info('All the checksums matched successfully' + for_verification_name ) class _lowerCAmelCase ( a ): """simple docstring""" class _lowerCAmelCase ( a ): """simple docstring""" class _lowerCAmelCase ( a ): """simple docstring""" class _lowerCAmelCase ( a ): """simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" if expected_splits is None: logger.info('Unable to verify splits sizes.' ) return if len(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreSplits(str(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) ) if len(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedSplits(str(set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) ) ) lowerCAmelCase__ :Optional[Any] = [ {'expected': expected_splits[name], 'recorded': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingSplitsSizesError(str(_SCREAMING_SNAKE_CASE ) ) logger.info('All the splits matched successfully.' ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True ) ->dict: """simple docstring""" if record_checksum: lowerCAmelCase__ :Tuple = shaaaa() with open(_SCREAMING_SNAKE_CASE , 'rb' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B'' ): m.update(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = m.hexdigest() else: lowerCAmelCase__ :Tuple = None return {"num_bytes": os.path.getsize(_SCREAMING_SNAKE_CASE ), "checksum": checksum} def __A (_SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
293
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
1
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , ): '''simple docstring''' super().__init__() self.register_modules(transformer=__UpperCAmelCase , vae=__UpperCAmelCase , scheduler=__UpperCAmelCase ) # create a imagenet -> id dictionary for easier use lowerCAmelCase__ :Optional[int] = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(',' ): lowerCAmelCase__ :Dict = int(__UpperCAmelCase ) lowerCAmelCase__ :Any = dict(sorted(self.labels.items() ) ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = list(__UpperCAmelCase ) for l in label: if l not in self.labels: raise ValueError( F"{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}." ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self , __UpperCAmelCase , __UpperCAmelCase = 4.0 , __UpperCAmelCase = None , __UpperCAmelCase = 5_0 , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = len(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.transformer.config.sample_size lowerCAmelCase__ :Union[str, Any] = self.transformer.config.in_channels lowerCAmelCase__ :Any = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=__UpperCAmelCase , device=self.device , dtype=self.transformer.dtype , ) lowerCAmelCase__ :Tuple = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents lowerCAmelCase__ :Tuple = torch.tensor(__UpperCAmelCase , device=self.device ).reshape(-1 ) lowerCAmelCase__ :Optional[int] = torch.tensor([1_0_0_0] * batch_size , device=self.device ) lowerCAmelCase__ :int = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(__UpperCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: lowerCAmelCase__ :Tuple = latent_model_input[: len(__UpperCAmelCase ) // 2] lowerCAmelCase__ :List[str] = torch.cat([half, half] , dim=0 ) lowerCAmelCase__ :List[str] = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = t if not torch.is_tensor(__UpperCAmelCase ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) lowerCAmelCase__ :List[str] = latent_model_input.device.type == 'mps' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :List[str] = torch.floataa if is_mps else torch.floataa else: lowerCAmelCase__ :List[str] = torch.intaa if is_mps else torch.intaa lowerCAmelCase__ :Optional[Any] = torch.tensor([timesteps] , dtype=__UpperCAmelCase , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: lowerCAmelCase__ :Optional[int] = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML lowerCAmelCase__ :Optional[int] = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output lowerCAmelCase__ :Optional[int] = self.transformer( __UpperCAmelCase , timestep=__UpperCAmelCase , class_labels=__UpperCAmelCase ).sample # perform guidance if guidance_scale > 1: lowerCAmelCase__ , lowerCAmelCase__ :Any = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = torch.split(__UpperCAmelCase , len(__UpperCAmelCase ) // 2 , dim=0 ) lowerCAmelCase__ :Any = uncond_eps + guidance_scale * (cond_eps - uncond_eps) lowerCAmelCase__ :int = torch.cat([half_eps, half_eps] , dim=0 ) lowerCAmelCase__ :Union[str, Any] = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: lowerCAmelCase__ , lowerCAmelCase__ :List[str] = torch.split(__UpperCAmelCase , __UpperCAmelCase , dim=1 ) else: lowerCAmelCase__ :str = noise_pred # compute previous image: x_t -> x_t-1 lowerCAmelCase__ :Dict = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample if guidance_scale > 1: lowerCAmelCase__ , lowerCAmelCase__ :str = latent_model_input.chunk(2 , dim=0 ) else: lowerCAmelCase__ :Optional[int] = latent_model_input lowerCAmelCase__ :Tuple = 1 / self.vae.config.scaling_factor * latents lowerCAmelCase__ :Dict = self.vae.decode(__UpperCAmelCase ).sample lowerCAmelCase__ :Union[str, Any] = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCAmelCase__ :List[str] = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowerCAmelCase__ :int = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (samples,) return ImagePipelineOutput(images=__UpperCAmelCase )
293
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], '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]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
1
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Optional[Any] = """vivit""" def __init__( self , __UpperCAmelCase=2_2_4 , __UpperCAmelCase=3_2 , __UpperCAmelCase=[2, 1_6, 1_6] , __UpperCAmelCase=3 , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu_fast" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-06 , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = hidden_size lowerCAmelCase__ :Optional[Any] = num_hidden_layers lowerCAmelCase__ :Dict = num_attention_heads lowerCAmelCase__ :Optional[Any] = intermediate_size lowerCAmelCase__ :Optional[Any] = hidden_act lowerCAmelCase__ :List[Any] = hidden_dropout_prob lowerCAmelCase__ :int = attention_probs_dropout_prob lowerCAmelCase__ :List[str] = initializer_range lowerCAmelCase__ :List[str] = layer_norm_eps lowerCAmelCase__ :List[str] = image_size lowerCAmelCase__ :Union[str, Any] = num_frames lowerCAmelCase__ :Optional[Any] = tubelet_size lowerCAmelCase__ :Union[str, Any] = num_channels lowerCAmelCase__ :int = qkv_bias super().__init__(**__UpperCAmelCase )
293
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
1
"""simple docstring""" import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() __A = 2 class _lowerCAmelCase : """simple docstring""" def __init__( self , *, # begin keyword-only arguments __UpperCAmelCase="<s>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase=None , ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = bos, unk, pad, eos lowerCAmelCase__ :int = [] lowerCAmelCase__ :Any = [] lowerCAmelCase__ :Dict = {} lowerCAmelCase__ :Tuple = self.add_symbol(__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = self.add_symbol(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self.add_symbol(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.add_symbol(__UpperCAmelCase ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(__UpperCAmelCase ) lowerCAmelCase__ :int = len(self.symbols ) def __eq__( self , __UpperCAmelCase ): '''simple docstring''' return self.indices == other.indices def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self ): '''simple docstring''' return len(self.symbols ) def __contains__( self , __UpperCAmelCase ): '''simple docstring''' return sym in self.indices @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = cls() d.add_from_file(__UpperCAmelCase ) return d def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=1 , __UpperCAmelCase=False ): '''simple docstring''' if word in self.indices and not overwrite: lowerCAmelCase__ :List[Any] = self.indices[word] lowerCAmelCase__ :str = self.count[idx] + n return idx else: lowerCAmelCase__ :List[str] = len(self.symbols ) lowerCAmelCase__ :Any = idx self.symbols.append(__UpperCAmelCase ) self.count.append(__UpperCAmelCase ) return idx def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): try: with open(__UpperCAmelCase , 'r' , encoding='utf-8' ) as fd: self.add_from_file(__UpperCAmelCase ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(__UpperCAmelCase ) ) return lowerCAmelCase__ :Union[str, Any] = f.readlines() lowerCAmelCase__ :Dict = self._load_meta(__UpperCAmelCase ) for line in lines[indices_start_line:]: try: lowerCAmelCase__ , lowerCAmelCase__ :List[str] = line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": lowerCAmelCase__ :List[Any] = True lowerCAmelCase__ , lowerCAmelCase__ :str = line.rsplit(' ' , 1 ) else: lowerCAmelCase__ :Any = False lowerCAmelCase__ :str = int(__UpperCAmelCase ) lowerCAmelCase__ :Any = line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(__UpperCAmelCase ) ) self.add_symbol(__UpperCAmelCase , n=__UpperCAmelCase , overwrite=__UpperCAmelCase ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = dict((re.sub(r'@@$' , '' , _SCREAMING_SNAKE_CASE ), v) if k.endswith('@@' ) else (re.sub(r'$' , '</w>' , _SCREAMING_SNAKE_CASE ), v) for k, v in d.items() ) lowerCAmelCase__ :List[Any] = '<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F"{k}</w>"] lowerCAmelCase__ :List[Any] = d[k] # restore return da def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if not os.path.exists(_SCREAMING_SNAKE_CASE ): raise ValueError(F"path {biogpt_checkpoint_path} does not exist!" ) os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) print(F"Writing results to {pytorch_dump_folder_path}" ) # handle various types of models lowerCAmelCase__ :Union[str, Any] = os.path.join(_SCREAMING_SNAKE_CASE , 'checkpoint.pt' ) if not os.path.isfile(_SCREAMING_SNAKE_CASE ): raise ValueError(F"path to the file {checkpoint_file} does not exist!" ) lowerCAmelCase__ :List[Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) lowerCAmelCase__ :Any = chkpt['cfg']['model'] # dicts lowerCAmelCase__ :int = os.path.join(_SCREAMING_SNAKE_CASE , 'dict.txt' ) if not os.path.isfile(_SCREAMING_SNAKE_CASE ): raise ValueError(F"path to the file {dict_file} does not exist!" ) lowerCAmelCase__ :str = Dictionary.load(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Tuple = rewrite_dict_keys(src_dict.indices ) lowerCAmelCase__ :Tuple = len(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = os.path.join(_SCREAMING_SNAKE_CASE , VOCAB_FILES_NAMES['vocab_file'] ) print(F"Generating {src_vocab_file} of {src_vocab_size} records" ) with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(_SCREAMING_SNAKE_CASE , ensure_ascii=_SCREAMING_SNAKE_CASE , indent=_SCREAMING_SNAKE_CASE ) ) # merges_file (bpecodes) lowerCAmelCase__ :List[str] = os.path.join(_SCREAMING_SNAKE_CASE , 'bpecodes' ) if not os.path.isfile(_SCREAMING_SNAKE_CASE ): raise ValueError(F"path to the file {bpecodes_file} does not exist!" ) lowerCAmelCase__ :List[Any] = os.path.join(_SCREAMING_SNAKE_CASE , VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # model config lowerCAmelCase__ :Any = os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) lowerCAmelCase__ :Optional[int] = { 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.0_2, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-12, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F"Generating {biogpt_model_config_file}" ) with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(_SCREAMING_SNAKE_CASE , ensure_ascii=_SCREAMING_SNAKE_CASE , indent=_SCREAMING_SNAKE_CASE ) ) # tokenizer config lowerCAmelCase__ :Optional[Any] = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = { 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F"Generating {biogpt_tokenizer_config_file}" ) with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(_SCREAMING_SNAKE_CASE , ensure_ascii=_SCREAMING_SNAKE_CASE , indent=_SCREAMING_SNAKE_CASE ) ) # model lowerCAmelCase__ :str = chkpt['model'] # remove unneeded keys lowerCAmelCase__ :List[Any] = [ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): lowerCAmelCase__ :List[Any] = model_state_dict.pop(_SCREAMING_SNAKE_CASE ) else: lowerCAmelCase__ :Any = model_state_dict.pop(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Tuple = BioGptConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :int = BioGptForCausalLM(_SCREAMING_SNAKE_CASE ) # check that it loads ok model_new.load_state_dict(_SCREAMING_SNAKE_CASE ) # save lowerCAmelCase__ :Any = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(F"Generating {pytorch_weights_dump_path}" ) torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print('Conversion is done!' ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--biogpt_checkpoint_path""", default=None, type=str, required=True, help=( """Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,""" """ bpecodes, etc.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
293
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
1
"""simple docstring""" from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def __A (_SCREAMING_SNAKE_CASE = "laptop" ) ->DataFrame: """simple docstring""" lowerCAmelCase__ :str = F"https://www.amazon.in/laptop/s?k={product}" lowerCAmelCase__ :Tuple = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } lowerCAmelCase__ :Optional[Any] = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).text ) # Initialize a Pandas dataframe with the column titles lowerCAmelCase__ :List[Any] = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' , attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} , ) , soup.find_all('div' , attrs={'class': 'a-row a-size-base a-color-base'} ) , ): try: lowerCAmelCase__ :Dict = item.ha.text lowerCAmelCase__ :Union[str, Any] = 'https://www.amazon.in/' + item.ha.a['href'] lowerCAmelCase__ :List[Any] = item.find('span' , attrs={'class': 'a-offscreen'} ).text try: lowerCAmelCase__ :List[Any] = item.find('span' , attrs={'class': 'a-icon-alt'} ).text except AttributeError: lowerCAmelCase__ :int = 'Not available' try: lowerCAmelCase__ :Optional[Any] = ( '₹' + item.find( 'span' , attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: lowerCAmelCase__ :Optional[int] = '' try: lowerCAmelCase__ :List[str] = float( ( ( float(product_mrp.strip('₹' ).replace(',' , '' ) ) - float(product_price.strip('₹' ).replace(',' , '' ) ) ) / float(product_mrp.strip('₹' ).replace(',' , '' ) ) ) * 100 ) except ValueError: lowerCAmelCase__ :Optional[Any] = float('nan' ) except AttributeError: pass lowerCAmelCase__ :int = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] lowerCAmelCase__ :Any = ' ' lowerCAmelCase__ :int = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": __A = """headphones""" get_amazon_product_data(product).to_csv(F'''Amazon Product Data for {product}.csv''')
293
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
1
"""simple docstring""" import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__UpperCAmelCase , 'hidden_sizes' ) ) self.parent.assertTrue(hasattr(__UpperCAmelCase , 'neck_hidden_sizes' ) ) self.parent.assertTrue(hasattr(__UpperCAmelCase , 'num_attention_heads' ) ) class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=1_3 , __UpperCAmelCase=3_2 , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=6_4_0 , __UpperCAmelCase=4 , __UpperCAmelCase="silu" , __UpperCAmelCase=3 , __UpperCAmelCase=3_2 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.02 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=1_0 , __UpperCAmelCase=None , ): '''simple docstring''' lowerCAmelCase__ :Any = parent lowerCAmelCase__ :Optional[int] = batch_size lowerCAmelCase__ :int = image_size lowerCAmelCase__ :List[Any] = patch_size lowerCAmelCase__ :Optional[int] = num_channels lowerCAmelCase__ :Optional[int] = last_hidden_size lowerCAmelCase__ :Optional[Any] = num_attention_heads lowerCAmelCase__ :Any = hidden_act lowerCAmelCase__ :Dict = conv_kernel_size lowerCAmelCase__ :Optional[Any] = output_stride lowerCAmelCase__ :List[Any] = hidden_dropout_prob lowerCAmelCase__ :Union[str, Any] = attention_probs_dropout_prob lowerCAmelCase__ :Optional[int] = classifier_dropout_prob lowerCAmelCase__ :int = use_labels lowerCAmelCase__ :int = is_training lowerCAmelCase__ :int = num_labels lowerCAmelCase__ :Any = initializer_range lowerCAmelCase__ :int = scope def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ :Optional[int] = None lowerCAmelCase__ :str = None if self.use_labels: lowerCAmelCase__ :Any = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCAmelCase__ :Optional[int] = self.get_config() return config, pixel_values, labels, pixel_labels def snake_case ( self ): '''simple docstring''' return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = MobileViTModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ :Union[str, Any] = model(__UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.num_labels lowerCAmelCase__ :List[str] = MobileViTForImageClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ :Optional[int] = model(__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.num_labels lowerCAmelCase__ :Union[str, Any] = MobileViTForSemanticSegmentation(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ :str = model(__UpperCAmelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCAmelCase__ :List[Any] = model(__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = config_and_inputs lowerCAmelCase__ :Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Dict = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) __magic_name__ :Optional[Any] = ( { """feature-extraction""": MobileViTModel, """image-classification""": MobileViTForImageClassification, """image-segmentation""": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) __magic_name__ :List[str] = False __magic_name__ :Optional[Any] = False __magic_name__ :Optional[int] = False __magic_name__ :int = False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = MobileViTModelTester(self ) lowerCAmelCase__ :List[str] = MobileViTConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='MobileViT does not use inputs_embeds' ) def snake_case ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileViT does not support input and output embeddings' ) def snake_case ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileViT does not output attentions' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :Any = model_class(__UpperCAmelCase ) lowerCAmelCase__ :str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ :List[str] = [*signature.parameters.keys()] lowerCAmelCase__ :Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' def check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :List[Any] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCAmelCase__ :List[Any] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) lowerCAmelCase__ :str = outputs.hidden_states lowerCAmelCase__ :Any = 5 self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCAmelCase__ :List[Any] = 2 for i in range(len(__UpperCAmelCase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :List[str] = True check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ :Tuple = True check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ :Optional[Any] = MobileViTModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def __A () ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ :List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case ( self ): '''simple docstring''' return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small' ) if is_vision_available() else None @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(__UpperCAmelCase ) lowerCAmelCase__ :str = self.default_image_processor lowerCAmelCase__ :Optional[Any] = prepare_img() lowerCAmelCase__ :Dict = image_processor(images=__UpperCAmelCase , return_tensors='pt' ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): lowerCAmelCase__ :str = model(**__UpperCAmelCase ) # verify the logits lowerCAmelCase__ :Optional[Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) lowerCAmelCase__ :Optional[int] = model.to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) lowerCAmelCase__ :Any = prepare_img() lowerCAmelCase__ :Any = image_processor(images=__UpperCAmelCase , return_tensors='pt' ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): lowerCAmelCase__ :List[str] = model(**__UpperCAmelCase ) lowerCAmelCase__ :Dict = outputs.logits # verify the logits lowerCAmelCase__ :List[Any] = torch.Size((1, 2_1, 3_2, 3_2) ) self.assertEqual(logits.shape , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = torch.tensor( [ [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]], [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]], [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]], ] , device=__UpperCAmelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) lowerCAmelCase__ :List[Any] = model.to(__UpperCAmelCase ) lowerCAmelCase__ :str = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) lowerCAmelCase__ :str = prepare_img() lowerCAmelCase__ :int = image_processor(images=__UpperCAmelCase , return_tensors='pt' ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): lowerCAmelCase__ :int = model(**__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = outputs.logits.detach().cpu() lowerCAmelCase__ :Tuple = image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase , target_sizes=[(5_0, 6_0)] ) lowerCAmelCase__ :Optional[int] = torch.Size((5_0, 6_0) ) self.assertEqual(segmentation[0].shape , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase ) lowerCAmelCase__ :str = torch.Size((3_2, 3_2) ) self.assertEqual(segmentation[0].shape , __UpperCAmelCase )
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
1
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black __A = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. __A = """ \"\"\" Output class for the scheduler's step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \"\"\" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None """ class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , 'schedulers/' ) ) lowerCAmelCase__ :List[str] = self.diffusers_dir shutil.copy( os.path.join(__UpperCAmelCase , 'src/diffusers/schedulers/scheduling_ddpm.py' ) , os.path.join(self.diffusers_dir , 'schedulers/scheduling_ddpm.py' ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'src/diffusers' shutil.rmtree(self.diffusers_dir ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = comment + F"\nclass {class_name}(nn.Module):\n" + class_code if overwrite_result is not None: lowerCAmelCase__ :Optional[Any] = comment + F"\nclass {class_name}(nn.Module):\n" + overwrite_result lowerCAmelCase__ :Dict = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 ) lowerCAmelCase__ :Tuple = black.format_str(__UpperCAmelCase , mode=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = os.path.join(self.diffusers_dir , 'new_code.py' ) with open(__UpperCAmelCase , 'w' , newline='\n' ) as f: f.write(__UpperCAmelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__UpperCAmelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__UpperCAmelCase ) with open(__UpperCAmelCase , 'r' ) as f: self.assertTrue(f.read() , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = check_copies.find_code_in_diffusers('schedulers.scheduling_ddpm.DDPMSchedulerOutput' ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' , 'DDPMSchedulerOutput' , REFERENCE_CODE + '\n' , ) # With no empty line at the end self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' , 'DDPMSchedulerOutput' , __UpperCAmelCase , ) # Copy consistency with rename self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' , 'TestSchedulerOutput' , re.sub('DDPM' , 'Test' , __UpperCAmelCase ) , ) # Copy consistency with a really long name lowerCAmelCase__ :Optional[int] = 'TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason' self.check_copy_consistency( F"# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}" , F"{long_class_name}SchedulerOutput" , re.sub('Bert' , __UpperCAmelCase , __UpperCAmelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' , 'TestSchedulerOutput' , __UpperCAmelCase , overwrite_result=re.sub('DDPM' , 'Test' , __UpperCAmelCase ) , )
293
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
1
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging __A = logging.get_logger(__name__) # pylint: disable=invalid-name class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' super().__init__() self.register_modules( vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , ) def snake_case ( self , __UpperCAmelCase = "auto" ): '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCAmelCase__ :Tuple = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.enable_attention_slicing(__UpperCAmelCase ) @torch.no_grad() def __call__( self , __UpperCAmelCase , __UpperCAmelCase = 5_1_2 , __UpperCAmelCase = 5_1_2 , __UpperCAmelCase = 5_0 , __UpperCAmelCase = 7.5 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :List[str] = 1 elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :List[str] = len(__UpperCAmelCase ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(__UpperCAmelCase )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__UpperCAmelCase , __UpperCAmelCase ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(__UpperCAmelCase )}." ) # get prompt text embeddings lowerCAmelCase__ :str = self.tokenizer( __UpperCAmelCase , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) lowerCAmelCase__ :Optional[int] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCAmelCase__ :List[str] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) lowerCAmelCase__ :Tuple = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: lowerCAmelCase__ :Any = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = text_embeddings.shape lowerCAmelCase__ :int = text_embeddings.repeat(1 , __UpperCAmelCase , 1 ) lowerCAmelCase__ :List[Any] = text_embeddings.view(bs_embed * num_images_per_prompt , __UpperCAmelCase , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. lowerCAmelCase__ :Tuple = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowerCAmelCase__ :List[str] if negative_prompt is None: lowerCAmelCase__ :int = [''] elif type(__UpperCAmelCase ) is not type(__UpperCAmelCase ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(__UpperCAmelCase )} !=" F" {type(__UpperCAmelCase )}." ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :str = [negative_prompt] elif batch_size != len(__UpperCAmelCase ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(__UpperCAmelCase )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" ' the batch size of `prompt`.' ) else: lowerCAmelCase__ :Union[str, Any] = negative_prompt lowerCAmelCase__ :Dict = text_input_ids.shape[-1] lowerCAmelCase__ :str = self.tokenizer( __UpperCAmelCase , padding='max_length' , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors='pt' , ) lowerCAmelCase__ :Union[str, Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCAmelCase__ :Optional[Any] = uncond_embeddings.shape[1] lowerCAmelCase__ :Optional[Any] = uncond_embeddings.repeat(__UpperCAmelCase , __UpperCAmelCase , 1 ) lowerCAmelCase__ :Dict = uncond_embeddings.view(batch_size * num_images_per_prompt , __UpperCAmelCase , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCAmelCase__ :List[Any] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. lowerCAmelCase__ :Optional[Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowerCAmelCase__ :Any = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 6_4, 6_4) lowerCAmelCase__ :Any = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowerCAmelCase__ :List[Any] = torch.randn( __UpperCAmelCase , generator=__UpperCAmelCase , device='cpu' , dtype=__UpperCAmelCase ).to(self.device ) lowerCAmelCase__ :Optional[int] = torch.randn(__UpperCAmelCase , generator=__UpperCAmelCase , device='cpu' , dtype=__UpperCAmelCase ).to( self.device ) else: lowerCAmelCase__ :List[Any] = torch.randn( __UpperCAmelCase , generator=__UpperCAmelCase , device=self.device , dtype=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = torch.randn(__UpperCAmelCase , generator=__UpperCAmelCase , device=self.device , dtype=__UpperCAmelCase ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) lowerCAmelCase__ :Any = latents_reference.to(self.device ) lowerCAmelCase__ :List[Any] = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images lowerCAmelCase__ :List[str] = (latents_shape[3] - latents_shape_reference[3]) // 2 lowerCAmelCase__ :Dict = (latents_shape[2] - latents_shape_reference[2]) // 2 lowerCAmelCase__ :Optional[Any] = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx lowerCAmelCase__ :str = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy lowerCAmelCase__ :Dict = 0 if dx < 0 else dx lowerCAmelCase__ :Optional[Any] = 0 if dy < 0 else dy lowerCAmelCase__ :int = max(-dx , 0 ) lowerCAmelCase__ :Optional[Any] = max(-dy , 0 ) # import pdb # pdb.set_trace() lowerCAmelCase__ :Optional[Any] = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(__UpperCAmelCase ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowerCAmelCase__ :Any = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCAmelCase__ :Optional[Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] lowerCAmelCase__ :List[Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCAmelCase__ :Optional[Any] = {} if accepts_eta: lowerCAmelCase__ :str = eta for i, t in enumerate(self.progress_bar(__UpperCAmelCase ) ): # expand the latents if we are doing classifier free guidance lowerCAmelCase__ :Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCAmelCase__ :Dict = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) # predict the noise residual lowerCAmelCase__ :int = self.unet(__UpperCAmelCase , __UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase ).sample # perform guidance if do_classifier_free_guidance: lowerCAmelCase__ , lowerCAmelCase__ :Dict = noise_pred.chunk(2 ) lowerCAmelCase__ :Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowerCAmelCase__ :Optional[Any] = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = 1 / 0.1_82_15 * latents lowerCAmelCase__ :Dict = self.vae.decode(__UpperCAmelCase ).sample lowerCAmelCase__ :Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCAmelCase__ :Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: lowerCAmelCase__ :Dict = self.feature_extractor(self.numpy_to_pil(__UpperCAmelCase ) , return_tensors='pt' ).to( self.device ) lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = self.safety_checker( images=__UpperCAmelCase , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: lowerCAmelCase__ :int = None if output_type == "pil": lowerCAmelCase__ :Optional[int] = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=__UpperCAmelCase , nsfw_content_detected=__UpperCAmelCase )
293
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
1
"""simple docstring""" 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 = logging.get_logger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->None: """simple docstring""" lowerCAmelCase__ :Dict = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ), F"{len(_SCREAMING_SNAKE_CASE )} != {len(_SCREAMING_SNAKE_CASE )}" dest_layers.load_state_dict(layers_to_copy.state_dict() ) __A = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 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, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __A = { # 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]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" try: lowerCAmelCase__ :Optional[Any] = 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(_SCREAMING_SNAKE_CASE ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[int]: """simple docstring""" 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(_SCREAMING_SNAKE_CASE ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "student" , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) ->Tuple[PreTrainedModel, List[int], List[int]]: """simple docstring""" lowerCAmelCase__ :Dict = '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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ).save_pretrained(_SCREAMING_SNAKE_CASE ) # purely for convenience lowerCAmelCase__ :List[Any] = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE ).eval() else: assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), F"teacher must be a model or string got type {type(_SCREAMING_SNAKE_CASE )}" lowerCAmelCase__ :List[Any] = teacher.config.to_diff_dict() try: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: lowerCAmelCase__ :Tuple = teacher_e if d is None: lowerCAmelCase__ :Optional[Any] = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d} ) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers' ): lowerCAmelCase__ , lowerCAmelCase__ :Dict = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: lowerCAmelCase__ , lowerCAmelCase__ :List[str] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: lowerCAmelCase__ :Any = teacher_e if d is None: lowerCAmelCase__ :List[Any] = 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(_SCREAMING_SNAKE_CASE ) # Copy weights lowerCAmelCase__ :Optional[Any] = teacher.config_class(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_config(_SCREAMING_SNAKE_CASE ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. lowerCAmelCase__ :Tuple = student.load_state_dict(teacher.state_dict() , strict=_SCREAMING_SNAKE_CASE ) 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 lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = list(range(_SCREAMING_SNAKE_CASE ) ), list(range(_SCREAMING_SNAKE_CASE ) ) 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(_SCREAMING_SNAKE_CASE ) 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: lowerCAmelCase__ :List[int] = pick_layers_to_copy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if d_layers_to_copy is None: lowerCAmelCase__ :List[int] = pick_layers_to_copy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) try: if hasattr( _SCREAMING_SNAKE_CASE , 'prophetnet' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , _SCREAMING_SNAKE_CASE ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , _SCREAMING_SNAKE_CASE ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , _SCREAMING_SNAKE_CASE ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , _SCREAMING_SNAKE_CASE ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , _SCREAMING_SNAKE_CASE ) copy_layers(teacher.decoder.block , student.decoder.block , _SCREAMING_SNAKE_CASE ) logger.info( F"Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}" ) lowerCAmelCase__ :Dict = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(_SCREAMING_SNAKE_CASE ) # 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)
293
"""simple docstring""" 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 _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = 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(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
1