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
from math import asin, atan, cos, radians, sin, sqrt, tan UpperCAmelCase__ = 637_8137.0 UpperCAmelCase__ = 635_6752.31_4245 UpperCAmelCase__ = 6378137 def _a ( a :float , a :float , a :float , a :float ) -> float: a = (AXIS_A - AXIS_B) / AXIS_A a = atan((1 - flattening) * tan(radians(a ) ) ) a = atan((1 - flattening) * tan(radians(a ) ) ) a = radians(a ) a = radians(a ) # Equation a = sin((phi_a - phi_a) / 2 ) a = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda a = sqrt(sin_sq_phi + (cos(a ) * cos(a ) * sin_sq_lambda) ) return 2 * RADIUS * asin(a ) if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' import os import sys __lowercase : List[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowercase : int = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[str] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoConfig.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoTokenizer.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : str , **_SCREAMING_SNAKE_CASE : Any ): return AutoTokenizer.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModel.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Union[str, Any] ): return AutoModel.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[Any] , **_SCREAMING_SNAKE_CASE : Optional[int] ): return AutoModelForCausalLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Union[str, Any] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoModelForMaskedLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Optional[Any] , **_SCREAMING_SNAKE_CASE : Any ): return AutoModelForSequenceClassification.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Any , **_SCREAMING_SNAKE_CASE : List[str] ): return AutoModelForQuestionAnswering.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
27
0
'''simple docstring''' import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCAmelCase_ ( snake_case_ : List[str] ) -> List[str]: '''simple docstring''' monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' class __A : def __init__(self : Dict , __a : Any ): UpperCAmelCase_ = metric_id class __A : a__ : Union[str, Any] = [MetricMock(UpperCamelCase__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def _lowercase (self : Optional[int] ): return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : Any , snake_case_ : Any , snake_case_ : Dict , snake_case_ : Tuple ) -> Optional[int]: '''simple docstring''' if "tmp_path" in args: UpperCAmelCase_ = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(snake_case_ , match="https://huggingface.co/docs/evaluate" ): func(*snake_case_ )
1
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = inspect.getfile(accelerate.test_utils ) __a : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __a : Union[str, Any] = test_metrics @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def __UpperCAmelCase ( self ): '''simple docstring''' self.test_metrics.main() @require_multi_gpu def __UpperCAmelCase ( self ): '''simple docstring''' print(f"""Found {torch.cuda.device_count()} devices.""" ) __a : List[Any] = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() )
27
0
'''simple docstring''' import math def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): lowercase__ = f"Input value of [number={number}] must be an integer" raise TypeError(A ) if number < 1: lowercase__ = f"Input value of [number={number}] must be > 0" raise ValueError(A ) elif number == 1: return 3 elif number == 2: return 5 else: lowercase__ = int(math.log(number // 3 , 2 ) ) + 2 lowercase__ = [3, 5] lowercase__ = 2 lowercase__ = 3 for block in range(1 , A ): for _ in range(A ): 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): lowerCamelCase : List[Any] = 0 try: lowerCamelCase : Dict = proth(number) except ValueError: print(f"""ValueError: there is no {number}th Proth number""") continue print(f"""The {number}th Proth number: {value}""")
2
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): __a : Optional[Any] = tmp_path / 'file.csv' __a : Union[str, Any] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : str = tmp_path / 'malformed_file.csv' __a : int = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = tmp_path / 'csv_with_image.csv' __a : Dict = textwrap.dedent( F"""\ image {image_file} """ ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Union[str, Any] = tmp_path / 'csv_with_label.csv' __a : Any = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Dict = tmp_path / 'csv_with_int_list.csv' __a : Tuple = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): __a : int = Csv() __a : str = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_SCREAMING_SNAKE_CASE , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(_SCREAMING_SNAKE_CASE ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1] __a : Tuple = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) __a : Any = csv._generate_tables([[csv_file_with_image]] ) __a : int = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() __a : Any = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1:] __a : Optional[int] = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) __a : List[str] = csv._generate_tables([[csv_file_with_label]] ) __a : Dict = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() __a : int = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(_SCREAMING_SNAKE_CASE ) for label in labels] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda _SCREAMING_SNAKE_CASE : [int(_SCREAMING_SNAKE_CASE ) for i in x.split()]} ) __a : Any = csv._generate_tables([[csv_file_with_int_list]] ) __a : Any = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) __a : Tuple = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
27
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : List[Any] = logging.get_logger(__name__) lowercase : List[Any] = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class A ( __snake_case ): __magic_name__ = '''unispeech''' def __init__( self , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE="group" , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.05 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=320 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=100 , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE="mean" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=80 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.5 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) A : Any = hidden_size A : Union[str, Any] = feat_extract_norm A : int = feat_extract_activation A : Tuple = list(SCREAMING_SNAKE_CASE ) A : Dict = list(SCREAMING_SNAKE_CASE ) A : Any = list(SCREAMING_SNAKE_CASE ) A : Any = conv_bias A : Dict = num_conv_pos_embeddings A : str = num_conv_pos_embedding_groups A : Optional[Any] = len(self.conv_dim ) A : str = num_hidden_layers A : Optional[Any] = intermediate_size A : Any = hidden_act A : List[str] = num_attention_heads A : int = hidden_dropout A : Optional[Any] = attention_dropout A : Union[str, Any] = activation_dropout A : str = feat_proj_dropout A : Tuple = final_dropout A : str = layerdrop A : Optional[int] = layer_norm_eps A : Optional[Any] = initializer_range A : Dict = num_ctc_classes A : int = vocab_size A : Dict = do_stable_layer_norm A : Dict = use_weighted_layer_sum A : Any = classifier_proj_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)`, but is `len(config.conv_dim) =''' F' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' F' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A : Dict = apply_spec_augment A : Tuple = mask_time_prob A : Dict = mask_time_length A : List[Any] = mask_time_min_masks A : List[Any] = mask_feature_prob A : List[str] = mask_feature_length A : Any = mask_feature_min_masks # parameters for pretraining with codevector quantized representations A : Dict = num_codevectors_per_group A : str = num_codevector_groups A : List[Any] = contrastive_logits_temperature A : Optional[Any] = feat_quantizer_dropout A : Union[str, Any] = num_negatives A : str = codevector_dim A : Tuple = proj_codevector_dim A : Optional[int] = diversity_loss_weight # ctc loss A : List[Any] = ctc_loss_reduction A : int = ctc_zero_infinity # pretraining loss A : Union[str, Any] = replace_prob @property def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
3
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Union[str, Any] = { 'configuration_blenderbot': [ 'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotConfig', 'BlenderbotOnnxConfig', ], 'tokenization_blenderbot': ['BlenderbotTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ['BlenderbotTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = [ 'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotForCausalLM', 'BlenderbotForConditionalGeneration', 'BlenderbotModel', 'BlenderbotPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ 'TFBlenderbotForConditionalGeneration', 'TFBlenderbotModel', 'TFBlenderbotPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Dict = [ 'FlaxBlenderbotForConditionalGeneration', 'FlaxBlenderbotModel', 'FlaxBlenderbotPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
'''simple docstring''' from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase_ : def __init__( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : str=1_3 , UpperCAmelCase__ : Dict=3_0 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : Dict=3 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : Any="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=1_0 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : Optional[Any]=0.6 , UpperCAmelCase__ : str=None , ) -> Any: lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = image_size lowerCAmelCase = patch_size lowerCAmelCase = num_channels lowerCAmelCase = is_training lowerCAmelCase = use_labels lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = type_sequence_label_size lowerCAmelCase = initializer_range lowerCAmelCase = mask_ratio lowerCAmelCase = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowerCAmelCase = (image_size // patch_size) ** 2 lowerCAmelCase = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def __UpperCAmelCase ( self : str ) -> Tuple: lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase = None if self.use_labels: lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self : Tuple ) -> int: return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_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 , mask_ratio=self.mask_ratio , ) def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ) -> Tuple: lowerCAmelCase = TFViTMAEModel(config=UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , training=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : str ) -> List[str]: lowerCAmelCase = TFViTMAEForPreTraining(UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , training=UpperCAmelCase__ ) # expected sequence length = num_patches lowerCAmelCase = (self.image_size // self.patch_size) ** 2 lowerCAmelCase = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images lowerCAmelCase = 1 lowerCAmelCase = TFViTMAEForPreTraining(UpperCAmelCase__ ) lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase = model(UpperCAmelCase__ , training=UpperCAmelCase__ ) lowerCAmelCase = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def __UpperCAmelCase ( self : Union[str, Any] ) -> int: lowerCAmelCase = self.prepare_config_and_inputs() ((lowerCAmelCase) , (lowerCAmelCase) , (lowerCAmelCase)) = config_and_inputs lowerCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ): lowerCamelCase : str = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () lowerCamelCase : List[str] = {'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {} lowerCamelCase : List[str] = False lowerCamelCase : Optional[int] = False lowerCamelCase : Optional[int] = False lowerCamelCase : str = False def __UpperCAmelCase ( self : Optional[int] ) -> Dict: lowerCAmelCase = TFViTMAEModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def __UpperCAmelCase ( self : Optional[Any] ) -> str: self.config_tester.run_common_tests() @unittest.skip(reason='ViTMAE does not use inputs_embeds' ) def __UpperCAmelCase ( self : Optional[int] ) -> Dict: pass def __UpperCAmelCase ( self : int ) -> Dict: lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , tf.keras.layers.Layer ) ) def __UpperCAmelCase ( self : Any ) -> Tuple: lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) lowerCAmelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase = [*signature.parameters.keys()] lowerCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def __UpperCAmelCase ( self : str ) -> int: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def __UpperCAmelCase ( self : str ) -> Union[str, Any]: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def __UpperCAmelCase ( self : str ) -> List[Any]: # make the mask reproducible np.random.seed(2 ) lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = int((config.image_size // config.patch_size) ** 2 ) lowerCAmelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) lowerCAmelCase = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , noise=UpperCAmelCase__ ) lowerCAmelCase = copy.deepcopy(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) lowerCAmelCase = model(**UpperCAmelCase__ , noise=UpperCAmelCase__ ) lowerCAmelCase = outputs_dict[0].numpy() lowerCAmelCase = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1E-6 ) def __UpperCAmelCase ( self : Optional[int] ) -> Optional[int]: # make the mask reproducible np.random.seed(2 ) lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = int((config.image_size // config.patch_size) ** 2 ) lowerCAmelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(UpperCAmelCase__ : Optional[int] ): lowerCAmelCase = {} for k, v in inputs_dict.items(): if tf.is_tensor(UpperCAmelCase__ ): lowerCAmelCase = v.numpy() else: lowerCAmelCase = np.array(UpperCAmelCase__ ) return inputs_np_dict for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) lowerCAmelCase = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = prepare_numpy_arrays(UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , noise=UpperCAmelCase__ ) lowerCAmelCase = model(**UpperCAmelCase__ , noise=UpperCAmelCase__ ) self.assert_outputs_same(UpperCAmelCase__ , UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any] ) -> Tuple: # make masks reproducible np.random.seed(2 ) lowerCAmelCase = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) lowerCAmelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowerCAmelCase = tf.constant(UpperCAmelCase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowerCAmelCase = tf_noise super().check_pt_tf_models(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def __UpperCAmelCase ( self : str ) -> Tuple: # make mask reproducible np.random.seed(2 ) lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(UpperCAmelCase__ ) if module_member_name.endswith('MainLayer' ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len('MainLayer' )] == model_class.__name__[: -len('Model' )] for module_member in (getattr(UpperCAmelCase__ , UpperCAmelCase__ ),) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(UpperCAmelCase__ , '_keras_serializable' , UpperCAmelCase__ ) } lowerCAmelCase = int((config.image_size // config.patch_size) ** 2 ) lowerCAmelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowerCAmelCase = tf.convert_to_tensor(UpperCAmelCase__ ) inputs_dict.update({'noise': noise} ) for main_layer_class in tf_main_layer_classes: lowerCAmelCase = main_layer_class(UpperCAmelCase__ ) lowerCAmelCase = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } lowerCAmelCase = tf.keras.Model(UpperCAmelCase__ , outputs=main_layer(UpperCAmelCase__ ) ) lowerCAmelCase = model(UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase = os.path.join(UpperCAmelCase__ , 'keras_model.h5' ) model.save(UpperCAmelCase__ ) lowerCAmelCase = tf.keras.models.load_model( UpperCAmelCase__ , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(UpperCAmelCase__ , tf.keras.Model ) lowerCAmelCase = model(UpperCAmelCase__ ) self.assert_outputs_same(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def __UpperCAmelCase ( self : Optional[int] ) -> List[str]: # make mask reproducible np.random.seed(2 ) lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = int((config.image_size // config.patch_size) ** 2 ) lowerCAmelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) lowerCAmelCase = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , noise=UpperCAmelCase__ ) if model_class.__name__ == "TFViTMAEModel": lowerCAmelCase = outputs.last_hidden_state.numpy() lowerCAmelCase = 0 else: lowerCAmelCase = outputs.logits.numpy() lowerCAmelCase = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCAmelCase__ , saved_model=UpperCAmelCase__ ) lowerCAmelCase = model_class.from_pretrained(UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , noise=UpperCAmelCase__ ) if model_class.__name__ == "TFViTMAEModel": lowerCAmelCase = after_outputs['last_hidden_state'].numpy() lowerCAmelCase = 0 else: lowerCAmelCase = after_outputs['logits'].numpy() lowerCAmelCase = 0 lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCAmelCase__ , 1E-5 ) def __UpperCAmelCase ( self : Any ) -> Union[str, Any]: # make mask reproducible np.random.seed(2 ) lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = int((config.image_size // config.patch_size) ** 2 ) lowerCAmelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) lowerCAmelCase = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , noise=UpperCAmelCase__ ) lowerCAmelCase = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(UpperCAmelCase__ ) lowerCAmelCase = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config lowerCAmelCase = model_class.from_config(model.config ) lowerCAmelCase = new_model(UpperCAmelCase__ ) # Build model new_model.set_weights(model.get_weights() ) lowerCAmelCase = new_model(UpperCAmelCase__ , noise=UpperCAmelCase__ ) self.assert_outputs_same(UpperCAmelCase__ , UpperCAmelCase__ ) @unittest.skip( reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' ) def __UpperCAmelCase ( self : Optional[Any] ) -> Tuple: pass @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load' ) def __UpperCAmelCase ( self : Tuple ) -> Union[str, Any]: pass @slow def __UpperCAmelCase ( self : Tuple ) -> Union[str, Any]: lowerCAmelCase = TFViTMAEModel.from_pretrained('google/vit-base-patch16-224' ) self.assertIsNotNone(UpperCAmelCase__ ) def a_ ( ): lowerCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class UpperCAmelCase_ ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: return ViTImageProcessor.from_pretrained('facebook/vit-mae-base' ) if is_vision_available() else None @slow def __UpperCAmelCase ( self : Tuple ) -> List[str]: # make random mask reproducible across the PT and TF model np.random.seed(2 ) lowerCAmelCase = TFViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base' ) lowerCAmelCase = self.default_image_processor lowerCAmelCase = prepare_img() lowerCAmelCase = image_processor(images=UpperCAmelCase__ , return_tensors='tf' ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowerCAmelCase = ViTMAEConfig() lowerCAmelCase = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) lowerCAmelCase = np.random.uniform(size=(1, num_patches) ) # forward pass lowerCAmelCase = model(**UpperCAmelCase__ , noise=UpperCAmelCase__ ) # verify the logits lowerCAmelCase = tf.convert_to_tensor([1, 1_9_6, 7_6_8] ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) lowerCAmelCase = tf.convert_to_tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , UpperCAmelCase__ , atol=1E-4 )
4
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase : def __init__( self , __a , __a=2 , __a=3 , __a=4 , __a=2 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=36 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=6 , __a=6 , __a=3 , __a=4 , __a=None , __a=1000 , ): '''simple docstring''' __a : Optional[Any] = parent __a : int = batch_size __a : Any = num_channels __a : Optional[int] = image_size __a : Dict = patch_size __a : int = is_training __a : Union[str, Any] = use_input_mask __a : Optional[int] = use_token_type_ids __a : Dict = use_labels __a : str = vocab_size __a : List[Any] = hidden_size __a : Union[str, Any] = num_hidden_layers __a : str = num_attention_heads __a : Union[str, Any] = intermediate_size __a : Any = hidden_act __a : List[str] = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : List[Any] = max_position_embeddings __a : Tuple = type_vocab_size __a : Any = type_sequence_label_size __a : Optional[int] = initializer_range __a : Any = coordinate_size __a : List[Any] = shape_size __a : Optional[int] = num_labels __a : Dict = num_choices __a : Union[str, Any] = scope __a : Union[str, Any] = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __a : Optional[int] = text_seq_length __a : Any = (image_size // patch_size) ** 2 + 1 __a : Dict = self.text_seq_length + self.image_seq_length def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __a : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __a : Any = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a : List[Any] = bbox[i, j, 3] __a : Tuple = bbox[i, j, 1] __a : str = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __a : int = bbox[i, j, 2] __a : Dict = bbox[i, j, 0] __a : int = tmp_coordinate __a : Optional[int] = tf.constant(__a ) __a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_input_mask: __a : Optional[Any] = random_attention_mask([self.batch_size, self.text_seq_length] ) __a : str = None if self.use_token_type_ids: __a : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __a : Optional[Any] = None __a : Optional[int] = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __a : int = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = TFLayoutLMvaModel(config=__a ) # text + image __a : List[Any] = model(__a , pixel_values=__a , training=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , training=__a , ) __a : Optional[int] = model(__a , bbox=__a , pixel_values=__a , training=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __a : Any = model(__a , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __a : str = model({'pixel_values': pixel_values} , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = TFLayoutLMvaForSequenceClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : str = self.num_labels __a : Optional[Any] = TFLayoutLMvaForTokenClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[Any] = 2 __a : Any = TFLayoutLMvaForQuestionAnswering(config=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , training=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a)) : Dict = config_and_inputs __a : Any = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) A_ = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) A_ = False A_ = False A_ = False def __UpperCAmelCase ( self , __a , __a , __a , __a , __a ): '''simple docstring''' return True def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : str = copy.deepcopy(__a ) if model_class in get_values(__a ): __a : str = { k: tf.tile(tf.expand_dims(__a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(__a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__a ): __a : Optional[int] = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : int = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __a : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Union[str, Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = TFLayoutLMvaModelTester(self ) __a : Optional[int] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) if getattr(__a , 'hf_compute_loss' , __a ): # The number of elements in the loss should be the same as the number of elements in the label __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=__a )[0] ] __a : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : Dict = prepared_for_class.pop('input_ids' ) __a : Tuple = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __a : Union[str, Any] = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __a : List[Any] = -100 __a : List[str] = tf.convert_to_tensor(__a ) __a : Any = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = model(__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __a : Tuple = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) # Get keys that were added with the _prepare_for_class function __a : Dict = prepared_for_class.keys() - inputs_dict.keys() __a : Any = inspect.signature(model.call ).parameters __a : str = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __a : List[Any] = {0: 'input_ids'} for label_key in label_keys: __a : List[Any] = signature_names.index(__a ) __a : Union[str, Any] = label_key __a : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __a : Union[str, Any] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __a : Optional[Any] = prepared_for_class[value] __a : str = tuple(__a ) # Send to model __a : Tuple = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a : Any = type self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( __a , __a , __a , __a , __a , __a , __a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = TFLayoutLMvaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__a ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __a : Tuple = self.default_image_processor __a : List[Any] = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ).pixel_values __a : Union[str, Any] = tf.constant([[1, 2]] ) __a : Optional[Any] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __a : Tuple = model(input_ids=__a , bbox=__a , pixel_values=__a , training=__a ) # verify the logits __a : List[Any] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , __a ) __a : Optional[Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , __a , atol=1E-4 ) )
27
0
import comet # From: unbabel-comet import torch import datasets UpperCAmelCase__ = datasets.logging.get_logger(__name__) UpperCAmelCase__ = '''\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = "{COMET}: A Neural Framework for {MT} Evaluation", author = "Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon", booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)", month = nov, year = "2020", address = "Online", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/2020.emnlp-main.213", pages = "2685--2702", } ''' UpperCAmelCase__ = '''\ Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM). With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. ''' UpperCAmelCase__ = ''' COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric(\'comet\') >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."] >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"] >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results["scores"]]) [0.19, 0.92] ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class lowerCamelCase__ ( datasets.Metric): def __A (self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://unbabel.github.io/COMET/html/index.html''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''sources''': datasets.Value('''string''' , id='''sequence''' ), '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/Unbabel/COMET'''] , reference_urls=[ '''https://github.com/Unbabel/COMET''', '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''', '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''', ] , ) def __A (self , UpperCAmelCase ) -> Dict: if self.config_name == "default": _lowercase =comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da''' ) ) else: _lowercase =comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=False ) -> int: if gpus is None: _lowercase =1 if torch.cuda.is_available() else 0 _lowercase ={'''src''': sources, '''mt''': predictions, '''ref''': references} _lowercase =[dict(zip(UpperCAmelCase , UpperCAmelCase ) ) for t in zip(*data.values() )] _lowercase , _lowercase =self.scorer.predict(UpperCAmelCase , gpus=UpperCAmelCase , progress_bar=UpperCAmelCase ) return {"mean_score": mean_score, "scores": scores}
5
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"""{test_file} instead.""" ) __a : Tuple = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __a : List[str] = components[:-1] + [test_fn.replace('.py' , '' )] __a : Optional[Any] = '.'.join(_SCREAMING_SNAKE_CASE ) return test_module_path def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = get_module_path(_SCREAMING_SNAKE_CASE ) __a : Dict = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = [] __a : List[str] = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : Any = [] __a : str = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): __a : int = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'all_model_classes' , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Tuple = test_class() if hasattr(_SCREAMING_SNAKE_CASE , 'setUp' ): test.setUp() __a : List[Any] = None if hasattr(_SCREAMING_SNAKE_CASE , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __a : List[str] = test.model_tester.__class__ return model_tester def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] ): __a : List[Any] = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [] for test_class in test_classes: __a : Any = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : str = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
27
0
from argparse import ArgumentParser from . import BaseTransformersCLICommand def __lowerCAmelCase ( a__ ) -> Union[str, Any]: return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __A( a ): @staticmethod def SCREAMING_SNAKE_CASE_ ( _snake_case ) -> int: '''simple docstring''' __a = parser.add_parser('''download''' ) download_parser.add_argument( '''--cache-dir''' , type=_snake_case , default=_snake_case , help='''Path to location to store the models''' ) download_parser.add_argument( '''--force''' , action='''store_true''' , help='''Force the model to be download even if already in cache-dir''' ) download_parser.add_argument( '''--trust-remote-code''' , action='''store_true''' , help='''Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine''' , ) download_parser.add_argument('''model''' , type=_snake_case , help='''Name of the model to download''' ) download_parser.set_defaults(func=_snake_case ) def __init__( self , _snake_case , _snake_case , _snake_case , _snake_case ) -> Dict: '''simple docstring''' __a = model __a = cache __a = force __a = trust_remote_code def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
6
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = StableDiffusionInpaintPipeline A_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS A_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS A_ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess A_ = frozenset([] ) def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__a , ) __a : str = PNDMScheduler(skip_prk_steps=__a ) torch.manual_seed(0 ) __a : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __a : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __a : Dict = CLIPTextModel(__a ) __a : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __a : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCAmelCase ( self , __a , __a=0 ): '''simple docstring''' __a : Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) __a : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a : Tuple = Image.fromarray(np.uinta(__a ) ).convert('RGB' ).resize((64, 64) ) __a : Tuple = Image.fromarray(np.uinta(image + 4 ) ).convert('RGB' ).resize((64, 64) ) if str(__a ).startswith('mps' ): __a : Any = torch.manual_seed(__a ) else: __a : str = torch.Generator(device=__a ).manual_seed(__a ) __a : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': init_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator __a : str = self.get_dummy_components() __a : Union[str, Any] = StableDiffusionInpaintPipeline(**__a ) __a : List[Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) __a : List[Any] = self.get_dummy_inputs(__a ) __a : Dict = sd_pipe(**__a ).images __a : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : List[Any] = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench.npy' ) __a : Optional[int] = 'stabilityai/stable-diffusion-2-inpainting' __a : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained(__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Dict = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : int = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench_fp16.npy' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : List[str] = StableDiffusionInpaintPipeline.from_pretrained( __a , torch_dtype=torch.floataa , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Union[str, Any] = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : int = torch.manual_seed(0 ) __a : Optional[Any] = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : int = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def __UpperCAmelCase ( self ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __a : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : Any = PNDMScheduler.from_pretrained(__a , subfolder='scheduler' ) __a : str = StableDiffusionInpaintPipeline.from_pretrained( __a , safety_checker=__a , scheduler=__a , torch_dtype=torch.floataa , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __a : str = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : str = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , num_inference_steps=2 , output_type='np' , ) __a : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
27
0
from __future__ import annotations import requests lowercase_ = set( "approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports".split() ) def _snake_case( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : str = "new" , SCREAMING_SNAKE_CASE__ : list | None = None ) -> dict: '''simple docstring''' A__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(SCREAMING_SNAKE_CASE__ ) - valid_terms ) ): A__ = f'Invalid search term: {invalid_search_terms}' raise ValueError(SCREAMING_SNAKE_CASE__ ) A__ = requests.get( f'https://reddit.com/r/{subreddit}/{age}.json?limit={limit}' , headers={'User-agent': 'A random string'} , ) if response.status_code == 429: raise requests.HTTPError A__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(SCREAMING_SNAKE_CASE__ )} A__ = {} for id_ in range(SCREAMING_SNAKE_CASE__ ): A__ = { item: data['data']['children'][id_]['data'][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
7
'''simple docstring''' import requests __lowercase : Tuple = '' # <-- Put your OpenWeatherMap appid here! __lowercase : Tuple = 'https://api.openweathermap.org/data/2.5/' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Chicago" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'weather' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Kolkata, India" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : float = 5_5.6_8 , _SCREAMING_SNAKE_CASE : float = 1_2.5_7 , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowercase : Dict = input('Enter a location:').strip() if location: pprint(current_weather(location)) else: break
27
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processing_git''': ['''GitProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GitForCausalLM''', '''GitModel''', '''GitPreTrainedModel''', '''GitVisionModel''', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
8
'''simple docstring''' import torch from transformers import AutoModel class __UpperCamelCase ( torch.nn.Module ): def __init__( self , __a="sayef/fsner-bert-base-uncased" ): '''simple docstring''' super(__a , self ).__init__() __a : Tuple = AutoModel.from_pretrained(__a , return_dict=__a ) __a : int = torch.nn.CosineSimilarity(3 , 1E-0_8 ) __a : Union[str, Any] = torch.nn.Softmax(dim=1 ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return self.bert(**__a ).last_hidden_state def __UpperCAmelCase ( self , __a ): '''simple docstring''' return token_embeddings.sum(2 , keepdim=__a ) def __UpperCAmelCase ( self , __a , __a , __a=1 ): '''simple docstring''' return self.softmax(T * self.cos(__a , __a ) ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : str = W_supports['sizes'].tolist() __a : Union[str, Any] = W_supports['start_token_id'].item() __a : Any = W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __a : Tuple = self.BERT(**__a ) __a : str = self.BERT(**__a ) __a : Any = None __a : Dict = None __a : Dict = W_supports['input_ids'] == start_token_id __a : Union[str, Any] = W_supports['input_ids'] == end_token_id for i, size in enumerate(__a ): if i == 0: __a : Optional[int] = 0 else: __a : Union[str, Any] = support_sizes[i - 1] __a : int = S[s : s + size][start_token_masks[s : s + size]] __a : Union[str, Any] = S[s : s + size][end_token_masks[s : s + size]] __a : Tuple = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __a : Dict = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __a : str = torch.vstack((p_starts, p_start) ) __a : str = torch.vstack((p_ends, p_end) ) else: __a : List[str] = p_start __a : int = p_end return p_starts, p_ends
27
0
from PIL import Image def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = image.size __SCREAMING_SNAKE_CASE : Optional[int] = 0 __SCREAMING_SNAKE_CASE : Optional[Any] = image.load() for i in range(lowercase__ ): for j in range(lowercase__ ): __SCREAMING_SNAKE_CASE : Tuple = pixels[j, i] mean += pixel mean //= width * height for j in range(lowercase__ ): for i in range(lowercase__ ): __SCREAMING_SNAKE_CASE : Optional[int] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": __lowerCAmelCase : Dict =mean_threshold(Image.open('path_to_image').convert('L')) image.save('output_image_path')
9
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 35 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : Optional[Any] = x_den * y_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : Optional[int] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : List[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Any = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Optional[int] = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 __a : int = x_num * y_num __a : Optional[Any] = x_den * y_num + x_num * y_den __a : Tuple = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : List[Any] = x_num * x_num * y_num * y_num __a : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : Optional[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
27
0
import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "segformer" def __init__(self : str , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : List[str]=4 , UpperCAmelCase_ : Any=[2, 2, 2, 2] , UpperCAmelCase_ : Dict=[8, 4, 2, 1] , UpperCAmelCase_ : Any=[32, 64, 160, 256] , UpperCAmelCase_ : Dict=[7, 3, 3, 3] , UpperCAmelCase_ : Any=[4, 2, 2, 2] , UpperCAmelCase_ : str=[1, 2, 5, 8] , UpperCAmelCase_ : Optional[Any]=[4, 4, 4, 4] , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Any=0.0 , UpperCAmelCase_ : Any=0.0 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Union[str, Any]=1E-6 , UpperCAmelCase_ : List[str]=256 , UpperCAmelCase_ : Union[str, Any]=255 , **UpperCAmelCase_ : Any , ) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( "Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be" " removed, as the behaviour will default to that of reshape_last_stage = True." , UpperCAmelCase_ , ) lowerCamelCase__: List[str] =num_channels lowerCamelCase__: int =num_encoder_blocks lowerCamelCase__: Union[str, Any] =depths lowerCamelCase__: List[Any] =sr_ratios lowerCamelCase__: Union[str, Any] =hidden_sizes lowerCamelCase__: Optional[int] =patch_sizes lowerCamelCase__: str =strides lowerCamelCase__: List[str] =mlp_ratios lowerCamelCase__: Tuple =num_attention_heads lowerCamelCase__: Optional[Any] =hidden_act lowerCamelCase__: Dict =hidden_dropout_prob lowerCamelCase__: str =attention_probs_dropout_prob lowerCamelCase__: List[str] =classifier_dropout_prob lowerCamelCase__: Tuple =initializer_range lowerCamelCase__: List[str] =drop_path_rate lowerCamelCase__: Optional[int] =layer_norm_eps lowerCamelCase__: Optional[int] =decoder_hidden_size lowerCamelCase__: List[Any] =kwargs.get("reshape_last_stage" , UpperCAmelCase_) lowerCamelCase__: List[Any] =semantic_loss_ignore_index class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE_ (self : int) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->float: '''simple docstring''' return 1E-4 @property def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int: '''simple docstring''' return 12
10
'''simple docstring''' import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): @property def __UpperCAmelCase ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ort.SessionOptions() __a : Dict = False return options def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) __a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default __a : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__a , feature_extractor=__a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__a ) __a : Tuple = 'A red cat sitting on a park bench' __a : int = np.random.RandomState(0 ) __a : Tuple = pipe( prompt=__a , image=__a , mask_image=__a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=__a , output_type='np' , ) __a : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
27
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = "dandelin/vilt-b32-finetuned-vqa" __SCREAMING_SNAKE_CASE = ( "This is a tool that answers a question about an image. It takes an input named `image` which should be the " "image containing the information, as well as a `question` which should be the question in English. It " "returns a text that is the answer to the question." ) __SCREAMING_SNAKE_CASE = "image_qa" __SCREAMING_SNAKE_CASE = AutoProcessor __SCREAMING_SNAKE_CASE = AutoModelForVisualQuestionAnswering __SCREAMING_SNAKE_CASE = ["image", "text"] __SCREAMING_SNAKE_CASE = ["text"] def __init__( self , *__lowerCamelCase , **__lowerCamelCase) -> int: requires_backends(self , ["vision"]) super().__init__(*__lowerCamelCase , **__lowerCamelCase) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase) -> Tuple: return self.pre_processor(__lowerCamelCase , __lowerCamelCase , return_tensors="pt") def _lowerCamelCase ( self , __lowerCamelCase) -> List[Any]: with torch.no_grad(): return self.model(**__lowerCamelCase).logits def _lowerCamelCase ( self , __lowerCamelCase) -> List[Any]: _A : str = outputs.argmax(-1).item() return self.model.config.idalabel[idx]
11
'''simple docstring''' import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowercase : Dict = 16 __lowercase : List[Any] = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return int(x / 2**20 ) class __UpperCamelCase : def __enter__( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero __a : Optional[int] = torch.cuda.memory_allocated() return self def __exit__( self , *__a ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() __a : Dict = torch.cuda.memory_allocated() __a : List[Any] = torch.cuda.max_memory_allocated() __a : Tuple = bamb(self.end - self.begin ) __a : Tuple = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def lowerCamelCase (_SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : int = 16 , _SCREAMING_SNAKE_CASE : str = "bert-base-cased" , _SCREAMING_SNAKE_CASE : int = 320 , _SCREAMING_SNAKE_CASE : int = 160 , ): __a : int = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : List[Any] = load_dataset( 'glue' , 'mrpc' , split={'train': F"""train[:{n_train}]""", 'validation': F"""validation[:{n_val}]"""} ) def tokenize_function(_SCREAMING_SNAKE_CASE : Tuple ): # max_length=None => use the model max length (it's actually the default) __a : Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a : List[str] = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=_SCREAMING_SNAKE_CASE ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : Tuple = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. __a : int = DataLoader( tokenized_datasets['train'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) __a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): # Initialize accelerator __a : str = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : Dict = config['lr'] __a : str = int(config['num_epochs'] ) __a : Optional[int] = int(config['seed'] ) __a : Any = int(config['batch_size'] ) __a : List[str] = args.model_name_or_path set_seed(_SCREAMING_SNAKE_CASE ) __a , __a : int = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : Optional[int] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE ) # Instantiate optimizer __a : Optional[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a : Optional[Any] = optimizer_cls(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) if accelerator.state.deepspeed_plugin is not None: __a : int = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: __a : Union[str, Any] = 1 __a : Tuple = (len(_SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a : str = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=0 , num_training_steps=_SCREAMING_SNAKE_CASE , ) else: __a : List[Any] = DummyScheduler(_SCREAMING_SNAKE_CASE , total_num_steps=_SCREAMING_SNAKE_CASE , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a : Optional[Any] = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # We need to keep track of how many total steps we have iterated over __a : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly __a : Dict = 0 # Now we train the model __a : str = {} for epoch in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): __a : List[Any] = model(**_SCREAMING_SNAKE_CASE ) __a : str = outputs.loss __a : str = loss / gradient_accumulation_steps accelerator.backward(_SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin ) ) ) accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used ) ) accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked ) ) accelerator.print( 'Total Peak Memory consumed during the train (max): {}'.format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) __a : List[Any] = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'peak_memory_utilization.json' ) , 'w' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : int = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=_SCREAMING_SNAKE_CASE , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_SCREAMING_SNAKE_CASE , ) parser.add_argument( '--output_dir' , type=_SCREAMING_SNAKE_CASE , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--peak_memory_upper_bound' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.' , ) parser.add_argument( '--n_train' , type=_SCREAMING_SNAKE_CASE , default=320 , help='Number of training examples to use.' , ) parser.add_argument( '--n_val' , type=_SCREAMING_SNAKE_CASE , default=160 , help='Number of validation examples to use.' , ) parser.add_argument( '--num_epochs' , type=_SCREAMING_SNAKE_CASE , default=1 , help='Number of train epochs.' , ) __a : List[str] = parser.parse_args() __a : List[Any] = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
27
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCamelCase__( __lowerCamelCase , unittest.TestCase): UpperCAmelCase__ : Tuple = ShapEImgaImgPipeline UpperCAmelCase__ : Optional[Any] = ['image'] UpperCAmelCase__ : int = ['image'] UpperCAmelCase__ : Any = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] UpperCAmelCase__ : int = False @property def lowerCAmelCase__ ( self: int ): return 32 @property def lowerCAmelCase__ ( self: List[str] ): return 32 @property def lowerCAmelCase__ ( self: Any ): return self.time_input_dim * 4 @property def lowerCAmelCase__ ( self: Dict ): return 8 @property def lowerCAmelCase__ ( self: int ): torch.manual_seed(0 ) __lowerCamelCase = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCamelCase = CLIPVisionModel(UpperCamelCase_ ) return model @property def lowerCAmelCase__ ( self: Dict ): __lowerCamelCase = CLIPImageProcessor( crop_size=2_24 , do_center_crop=UpperCamelCase_ , do_normalize=UpperCamelCase_ , do_resize=UpperCamelCase_ , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=2_24 , ) return image_processor @property def lowerCAmelCase__ ( self: Tuple ): torch.manual_seed(0 ) __lowerCamelCase = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } __lowerCamelCase = PriorTransformer(**UpperCamelCase_ ) return model @property def lowerCAmelCase__ ( self: List[Any] ): torch.manual_seed(0 ) __lowerCamelCase = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } __lowerCamelCase = ShapERenderer(**UpperCamelCase_ ) return model def lowerCAmelCase__ ( self: List[str] ): __lowerCamelCase = self.dummy_prior __lowerCamelCase = self.dummy_image_encoder __lowerCamelCase = self.dummy_image_processor __lowerCamelCase = self.dummy_renderer __lowerCamelCase = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=10_24 , prediction_type="""sample""" , use_karras_sigmas=UpperCamelCase_ , clip_sample=UpperCamelCase_ , clip_sample_range=1.0 , ) __lowerCamelCase = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def lowerCAmelCase__ ( self: int , UpperCamelCase_: List[Any] , UpperCamelCase_: Dict=0 ): __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase_ ) ).to(UpperCamelCase_ ) if str(UpperCamelCase_ ).startswith("""mps""" ): __lowerCamelCase = torch.manual_seed(UpperCamelCase_ ) else: __lowerCamelCase = torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ ) __lowerCamelCase = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def lowerCAmelCase__ ( self: Tuple ): __lowerCamelCase = """cpu""" __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**UpperCamelCase_ ) __lowerCamelCase = pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) __lowerCamelCase = pipe(**self.get_dummy_inputs(UpperCamelCase_ ) ) __lowerCamelCase = output.images[0] __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCamelCase = np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase__ ( self: List[str] ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCAmelCase__ ( self: Any ): __lowerCamelCase = torch_device == """cpu""" __lowerCamelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCamelCase_ , relax_max_difference=UpperCamelCase_ , ) def lowerCAmelCase__ ( self: Any ): __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**UpperCamelCase_ ) __lowerCamelCase = pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) __lowerCamelCase = 1 __lowerCamelCase = 2 __lowerCamelCase = self.get_dummy_inputs(UpperCamelCase_ ) for key in inputs.keys(): if key in self.batch_params: __lowerCamelCase = batch_size * [inputs[key]] __lowerCamelCase = pipe(**UpperCamelCase_ , num_images_per_prompt=UpperCamelCase_ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCamelCase__( unittest.TestCase): def lowerCAmelCase__ ( self: Union[str, Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self: Any ): __lowerCamelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) __lowerCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) __lowerCamelCase = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) __lowerCamelCase = pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) __lowerCamelCase = torch.Generator(device=UpperCamelCase_ ).manual_seed(0 ) __lowerCamelCase = pipe( UpperCamelCase_ , generator=UpperCamelCase_ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(UpperCamelCase_ , UpperCamelCase_ )
12
'''simple docstring''' import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer __lowercase : List[Any] = 'bart' __lowercase : Union[str, Any] = True @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : List[Any] = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) __a : Dict = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) __a : Optional[int] = qar_model.eval() else: __a , __a : str = (None, None) if MODEL_TYPE == "bart": __a : Union[str, Any] = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) __a : int = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) __a : Optional[Any] = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) __a : str = sas_model.eval() else: __a , __a : Tuple = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : Optional[Any] = faiss.StandardGpuResources() __a : Dict = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] __a : int = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 128) , ) __a : int = faiss.IndexFlatIP(128 ) __a : Any = faiss.index_cpu_to_gpu(_SCREAMING_SNAKE_CASE , 1 , _SCREAMING_SNAKE_CASE ) wikiaab_gpu_index_flat.add(_SCREAMING_SNAKE_CASE ) # TODO fix for larger GPU else: __a , __a : str = (None, None) __a : Optional[int] = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : Dict = datasets.load_dataset('eli5' , name='LFQA_reddit' ) __a : Dict = elia['train_eli5'] __a : Optional[int] = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 128) ) __a : str = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(_SCREAMING_SNAKE_CASE ) return (elia_train, eli5_train_q_index) __lowercase , __lowercase , __lowercase : Any = load_indexes() __lowercase , __lowercase , __lowercase , __lowercase : Dict = load_models() __lowercase , __lowercase : int = load_train_data() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str]=10 ): __a : Optional[int] = embed_questions_for_retrieval([question] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a , __a : Union[str, Any] = eli5_train_q_index.search(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [elia_train[int(_SCREAMING_SNAKE_CASE )] for i in I[0]] return nn_examples def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : str="wiki40b" , _SCREAMING_SNAKE_CASE : List[str]="dense" , _SCREAMING_SNAKE_CASE : Any=10 ): if source == "none": __a , __a : Any = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": __a , __a : str = query_qa_dense_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a , __a : Union[str, Any] = query_es_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index_name='english_wiki40b_snippets_100w' , n_results=_SCREAMING_SNAKE_CASE , ) __a : Dict = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] __a : Any = 'question: {} context: {}'.format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda _SCREAMING_SNAKE_CASE : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _SCREAMING_SNAKE_CASE : None), } ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Dict=64 , _SCREAMING_SNAKE_CASE : Dict=256 , _SCREAMING_SNAKE_CASE : Any=False , _SCREAMING_SNAKE_CASE : Tuple=2 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0.9_5 , _SCREAMING_SNAKE_CASE : str=0.8 ): with torch.no_grad(): __a : Union[str, Any] = qa_sas_generate( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , num_answers=1 , num_beams=_SCREAMING_SNAKE_CASE , min_len=_SCREAMING_SNAKE_CASE , max_len=_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE , temp=_SCREAMING_SNAKE_CASE , top_p=_SCREAMING_SNAKE_CASE , top_k=_SCREAMING_SNAKE_CASE , max_input_length=1_024 , device='cuda:0' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar __lowercase : Optional[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' __lowercase : str = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia __lowercase : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) __lowercase : Dict = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] __lowercase : Union[str, Any] = st.sidebar.checkbox('Demo options') if demo_options: __lowercase : Any = st.sidebar.selectbox( '', action_list, index=3, ) __lowercase : Tuple = action_list.index(action_st) __lowercase : Tuple = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) __lowercase : List[Any] = show_type == 'Show full text of passages' else: __lowercase : int = 3 __lowercase : str = True __lowercase : Tuple = st.sidebar.checkbox('Retrieval options') if retrieval_options: __lowercase : List[Any] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: __lowercase : str = 'wiki40b' __lowercase : List[Any] = 'dense' __lowercase : Dict = 'beam' __lowercase : Optional[int] = 2 __lowercase : List[str] = 64 __lowercase : Tuple = 2_56 __lowercase : List[str] = None __lowercase : Tuple = None __lowercase : List[Any] = st.sidebar.checkbox('Generation options') if generate_options: __lowercase : Optional[Any] = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) __lowercase : List[Any] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) __lowercase : Tuple = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=2_56, value=64, step=8, format=None, key=None ) __lowercase : int = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None ) if sampled == "beam": __lowercase : Any = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: __lowercase : Dict = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) __lowercase : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) __lowercase : List[str] = None # start main text __lowercase : int = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] __lowercase : Optional[int] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": __lowercase : Any = st.text_input('Enter your question here:', '') else: __lowercase : Any = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": __lowercase , __lowercase : Optional[int] = make_support(question, source=wiki_source, method='dense', n_results=10) __lowercase , __lowercase : List[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) __lowercase : Optional[int] = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] __lowercase : str = support_list[:10] __lowercase : Optional[int] = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: __lowercase , __lowercase : Optional[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: __lowercase , __lowercase : int = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): __lowercase : str = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) __lowercase : Any = res[1].strip() if sec_titles == "": __lowercase : List[str] = '[{}]({})'.format(res[0], wiki_url) else: __lowercase : Union[str, Any] = sec_titles.split(' & ') __lowercase : str = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: __lowercase : str = find_nearest_training(question) __lowercase : Optional[int] = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) __lowercase : Any = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) __lowercase : List[Any] = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
27
0
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 __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): SCREAMING_SNAKE_CASE_: int = "laion/clap-htsat-unfused" SCREAMING_SNAKE_CASE_: Optional[int] = tempfile.mkdtemp() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **lowerCAmelCase__ : Optional[Any]): return RobertaTokenizer.from_pretrained(self.checkpoint , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Tuple , **lowerCAmelCase__ : List[Any]): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): shutil.rmtree(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE_: Union[str, Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE_: Tuple = ClapProcessor(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_: Optional[int] = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , lowerCAmelCase__) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[str]): SCREAMING_SNAKE_CASE_: int = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_: Dict = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") SCREAMING_SNAKE_CASE_: Optional[int] = self.get_feature_extractor(do_normalize=lowerCAmelCase__ , padding_value=1.0) SCREAMING_SNAKE_CASE_: Tuple = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=lowerCAmelCase__ , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , lowerCAmelCase__) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : str): SCREAMING_SNAKE_CASE_: Tuple = self.get_feature_extractor() SCREAMING_SNAKE_CASE_: Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE_: Union[str, Any] = ClapProcessor(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = floats_list((3, 1000)) SCREAMING_SNAKE_CASE_: Union[str, Any] = feature_extractor(lowerCAmelCase__ , return_tensors="np") SCREAMING_SNAKE_CASE_: List[Any] = processor(audios=lowerCAmelCase__ , return_tensors="np") for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2) def _SCREAMING_SNAKE_CASE ( self : List[str]): SCREAMING_SNAKE_CASE_: List[str] = self.get_feature_extractor() SCREAMING_SNAKE_CASE_: int = self.get_tokenizer() SCREAMING_SNAKE_CASE_: Tuple = ClapProcessor(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = "This is a test string" SCREAMING_SNAKE_CASE_: int = processor(text=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = tokenizer(lowerCAmelCase__) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def _SCREAMING_SNAKE_CASE ( self : List[Any]): SCREAMING_SNAKE_CASE_: Optional[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE_: Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE_: str = ClapProcessor(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE_: Union[str, Any] = processor.batch_decode(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = tokenizer.batch_decode(lowerCAmelCase__) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): SCREAMING_SNAKE_CASE_: str = self.get_feature_extractor() SCREAMING_SNAKE_CASE_: List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_: Dict = ClapProcessor(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , )
13
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __lowercase : Tuple = logging.get_logger(__name__) __lowercase : List[Any] = torch.device('cpu') def lowerCamelCase (): __a : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __a : Tuple = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0, 8.8_6_8_5e-0_1, 2.4_3_6_0e-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6e-0_1, 2.3_4_7_8e-0_1, -1.6_9_6_3e0_0, -1.7_3_8_1e0_0, -8.6_3_3_7e-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8e-0_1, -4.7_4_2_9e-0_1, -1.0_8_9_7e0_0, -1.0_2_4_8e0_0, 3.5_5_2_3e-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0e-0_1, 2.4_2_1_1e-0_1, -6.0_1_8_5e-0_1, -8.2_7_8_9e-0_1, -6.0_4_4_6e-0_2] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : int = dct.pop(_SCREAMING_SNAKE_CASE ) __a : Tuple = val def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : Dict = [] for k in state_dict.keys(): __a : List[Any] = k if ".pwconv" in k: __a : List[Any] = k_new.replace('.pwconv' , '.point_wise_conv' ) if ".dwconv" in k: __a : Dict = k_new.replace('.dwconv' , '.depth_wise_conv' ) if ".Proj." in k: __a : Optional[int] = k_new.replace('.Proj.' , '.proj.' ) if "patch_embed" in k_new: __a : List[Any] = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' ) if "network" in k_new: __a : Union[str, Any] = k_new.split('.' ) if ls[2].isdigit(): __a : Union[str, Any] = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] ) else: __a : Union[str, Any] = k_new.replace('network' , 'swiftformer.encoder.network' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Union[str, Any] = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size __a : List[str] = 1_000 __a : Tuple = 'huggingface/label-files' __a : str = 'imagenet-1k-id2label.json' __a : Dict = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) __a : Optional[int] = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a : Any = idalabel __a : str = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": __a : Dict = [3, 3, 6, 4] __a : int = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": __a : Dict = [3, 3, 9, 6] __a : List[str] = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": __a : Dict = [4, 3, 10, 5] __a : Optional[int] = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": __a : Tuple = [4, 4, 12, 6] __a : Dict = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('https' ): __a : List[Any] = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE ) else: __a : Union[str, Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) __a : Optional[Any] = checkpoint __a : Dict = create_rename_keys(_SCREAMING_SNAKE_CASE ) for rename_key_src, rename_key_dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model __a : Tuple = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval() hf_model.load_state_dict(_SCREAMING_SNAKE_CASE ) # prepare test inputs __a : Tuple = prepare_img() __a : str = ViTImageProcessor.from_pretrained('preprocessor_config' ) __a : Tuple = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # compare outputs from both models __a : List[Any] = get_expected_output(_SCREAMING_SNAKE_CASE ) __a : Dict = hf_model(inputs['pixel_values'] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swiftformer_name', default='swiftformer_xs', choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'], type=str, help='Name of the SwiftFormer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='./converted_outputs/', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.') __lowercase : Tuple = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
27
0
print((lambda quine: quine % quine)("""print((lambda quine: quine %% quine)(%r))"""))
14
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __lowercase : Dict = logging.get_logger(__name__) __lowercase : Optional[Any] = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "umt5" A_ = ["past_key_values"] def __init__( self , __a=25_0112 , __a=512 , __a=64 , __a=1024 , __a=8 , __a=None , __a=6 , __a=32 , __a=128 , __a=0.1 , __a=1E-6 , __a=1.0 , __a="gated-gelu" , __a=True , __a=True , __a="T5Tokenizer" , __a=True , __a=0 , __a=1 , __a=0 , **__a , ): '''simple docstring''' super().__init__( is_encoder_decoder=__a , tokenizer_class=__a , tie_word_embeddings=__a , pad_token_id=__a , eos_token_id=__a , decoder_start_token_id=__a , **__a , ) __a : Any = vocab_size __a : Any = d_model __a : str = d_kv __a : Dict = d_ff __a : Union[str, Any] = num_layers __a : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __a : Optional[int] = num_heads __a : Tuple = relative_attention_num_buckets __a : Optional[Any] = relative_attention_max_distance __a : Optional[int] = dropout_rate __a : List[Any] = layer_norm_epsilon __a : int = initializer_factor __a : Union[str, Any] = feed_forward_proj __a : Any = use_cache __a : List[Any] = self.feed_forward_proj.split('-' ) __a : Dict = act_info[-1] __a : Dict = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) if feed_forward_proj == "gated-gelu": __a : Optional[int] = 'gelu_new' @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.d_model @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_heads @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_layers class __UpperCamelCase ( lowerCAmelCase_ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __a : Dict = 'past_encoder_sequence + sequence' __a : Tuple = {0: 'batch'} __a : Tuple = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __a : List[Any] = {0: 'batch', 1: 'decoder_sequence'} __a : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __UpperCAmelCase ( self ): '''simple docstring''' return 13 @property def __UpperCAmelCase ( self ): '''simple docstring''' return 5E-4
27
0
from __future__ import annotations from collections.abc import Generator def UpperCAmelCase ( ) -> Generator[int, None, None]: """simple docstring""" __A = {} __A = 2 while True: __A = factor_map.pop(a_ , a_ ) if factor: __A = factor + prime while x in factor_map: x += factor __A = factor else: __A = prime yield prime prime += 1 def UpperCAmelCase ( a_ = 1E10 ) -> int: """simple docstring""" __A = sieve() __A = 1 while True: __A = next(a_ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(a_ ) n += 2 if __name__ == "__main__": print(solution())
15
'''simple docstring''' import requests from bsa import BeautifulSoup def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "https://www.worldometers.info/coronavirus" ): __a : List[Any] = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE ).text , 'html.parser' ) __a : Union[str, Any] = soup.findAll('h1' ) __a : int = soup.findAll('div' , {'class': 'maincounter-number'} ) keys += soup.findAll('span' , {'class': 'panel-title'} ) values += soup.findAll('div' , {'class': 'number-table-main'} ) return {key.text.strip(): value.text.strip() for key, value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
27
0
"""simple docstring""" def __UpperCAmelCase ( __lowerCamelCase = 1_00 ) -> int: lowercase__ : List[str] = set() lowercase__ : Dict = 0 lowercase__ : Dict = n + 1 # maximum limit for a in range(2 , __lowerCamelCase ): for b in range(2 , __lowerCamelCase ): lowercase__ : Tuple = a**b # calculates the current power collect_powers.add(__lowerCamelCase ) # adds the result to the set return len(__lowerCamelCase ) if __name__ == "__main__": print('Number of terms ', solution(int(str(input()).strip())))
16
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__a , 'embed_dim' ) ) self.parent.assertTrue(hasattr(__a , 'num_heads' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=64 , __a=3 , __a=[16, 48, 96] , __a=[1, 3, 6] , __a=[1, 2, 10] , __a=[7, 3, 3] , __a=[4, 2, 2] , __a=[2, 1, 1] , __a=[2, 2, 2] , __a=[False, False, True] , __a=[0.0, 0.0, 0.0] , __a=0.02 , __a=1E-1_2 , __a=True , __a=True , __a=2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : Optional[int] = image_size __a : List[str] = patch_sizes __a : str = patch_stride __a : Any = patch_padding __a : Dict = is_training __a : Union[str, Any] = use_labels __a : Dict = num_labels __a : List[Any] = num_channels __a : Any = embed_dim __a : int = num_heads __a : Optional[int] = stride_kv __a : Dict = depth __a : List[str] = cls_token __a : List[Any] = attention_drop_rate __a : Tuple = initializer_range __a : int = layer_norm_eps def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Dict = None if self.use_labels: # create a random int32 tensor of given shape __a : str = ids_tensor([self.batch_size] , self.num_labels ) __a : str = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = TFCvtModel(config=__a ) __a : Dict = model(__a , training=__a ) __a : Any = (self.image_size, self.image_size) __a , __a : Dict = image_size[0], image_size[1] for i in range(len(self.depth ) ): __a : Tuple = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) __a : str = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : List[Any] = self.num_labels __a : Optional[int] = TFCvtForImageClassification(__a ) __a : Dict = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () A_ = ( {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification} if is_tf_available() else {} ) A_ = False A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtModelTester(self ) __a : List[Any] = TFCvtConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason='Cvt does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = tf.keras.mixed_precision.Policy('mixed_float16' ) tf.keras.mixed_precision.set_global_policy(__a ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('float32' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : List[str] = model_class(__a ) __a : Union[str, Any] = model(**self._prepare_for_class(__a , __a ) ) __a : Any = outputs.hidden_states __a : Union[str, Any] = len(self.model_tester.depth ) self.assertEqual(len(__a ) , __a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[str] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[Any] = TFCvtModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __a : Tuple = self.default_image_processor __a : Any = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ) # forward pass __a : Any = model(**__a ) # verify the logits __a : Any = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __a : Optional[Any] = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __a , atol=1E-4 ) )
27
0
"""simple docstring""" from __future__ import annotations from math import pow, sqrt def _A ( UpperCamelCase_ : float, UpperCamelCase_ : float, UpperCamelCase_ : float) -> dict[str, float]: '''simple docstring''' if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance == 0: return {"resistance": sqrt(pow(UpperCamelCase_, 2) - pow(UpperCamelCase_, 2))} elif reactance == 0: return {"reactance": sqrt(pow(UpperCamelCase_, 2) - pow(UpperCamelCase_, 2))} elif impedance == 0: return {"impedance": sqrt(pow(UpperCamelCase_, 2) + pow(UpperCamelCase_, 2))} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
17
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __lowercase : Union[str, Any] = logging.get_logger(__name__) __lowercase : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } __lowercase : Optional[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): for attribute in key.split('.' ): __a : Any = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: __a : Any = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __a : Tuple = value elif weight_type == "weight_g": __a : str = value elif weight_type == "weight_v": __a : Optional[Any] = value elif weight_type == "bias": __a : Union[str, Any] = value else: __a : List[Any] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : int = [] __a : List[str] = fairseq_model.state_dict() __a : Tuple = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight __a : int = None for name, value in fairseq_dict.items(): __a : List[str] = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == 'group' , ) __a : List[str] = True elif name.split('.' )[0] == "proj": __a : Tuple = fairseq_model.proj __a : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __a : List[Any] = True if "*" in mapped_key: __a : str = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2] __a : int = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: __a : List[Any] = 'weight_g' elif "weight_v" in name: __a : List[Any] = 'weight_v' elif "bias" in name: __a : Optional[Any] = 'bias' elif "weight" in name: __a : Tuple = 'weight' else: __a : Optional[Any] = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : List[str] = full_name.split('conv_layers.' )[-1] __a : Any = name.split('.' ) __a : List[str] = int(items[0] ) __a : List[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __a : List[str] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __a : str = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) __a : Tuple = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __a : List[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a , __a : List[str] = emb.weight.shape __a : str = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) __a : Optional[int] = emb.weight.data return lin_layer def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any ): with open(_SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' ) as f: __a : Union[str, Any] = f.readlines() __a : Tuple = [line.split(' ' )[0] for line in lines] __a : int = len(_SCREAMING_SNAKE_CASE ) __a : List[Any] = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(_SCREAMING_SNAKE_CASE , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int] , ): __a : Optional[int] = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : Any = SpeechaTextaConfig.from_pretrained( _SCREAMING_SNAKE_CASE , vocab_size=_SCREAMING_SNAKE_CASE , decoder_layers=_SCREAMING_SNAKE_CASE , do_stable_layer_norm=_SCREAMING_SNAKE_CASE ) __a : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) __a , __a , __a : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) __a : Optional[int] = model[0].eval() # set weights for wav2vec2 encoder __a : Tuple = WavaVecaModel(_SCREAMING_SNAKE_CASE ) __a : int = recursively_load_weights_wavaveca(model.encoder , _SCREAMING_SNAKE_CASE ) __a : Dict = SpeechaTextaForCausalLM(_SCREAMING_SNAKE_CASE ) __a , __a : Optional[int] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_SCREAMING_SNAKE_CASE ) # set output linear layer unexpected_keys.remove('embed_out' ) __a : Optional[Any] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) __a : Tuple = SpeechEncoderDecoderModel(encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) __a : int = False # add projection layer __a : str = nn.Parameter(projection_layer.weight ) __a : Any = nn.Parameter(projection_layer.bias ) __a : str = create_vocab_dict(_SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) , 'w' ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = SpeechaTextaTokenizer(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) ) tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = hf_wavavec.config.to_dict() __a : Tuple = tokenizer.pad_token_id __a : Optional[int] = tokenizer.bos_token_id __a : Union[str, Any] = tokenizer.eos_token_id __a : Tuple = 'speech_to_text_2' __a : Tuple = 'wav2vec2' __a : List[str] = SpeechEncoderDecoderConfig.from_dict(_SCREAMING_SNAKE_CASE ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-large-lv60', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/s2t-small-mustc-en-fr-st', type=str, help='Path to hf decoder s2t checkpoint config', ) parser.add_argument('--vocab_size', default=1_02_24, type=int, help='Vocab size of decoder') parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers') __lowercase : Tuple = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
27
0
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _snake_case ( lowerCAmelCase : Dict ): """simple docstring""" if ( (cp >= 0X4_E_0_0 and cp <= 0X9_F_F_F) or (cp >= 0X3_4_0_0 and cp <= 0X4_D_B_F) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_A_6_D_F) # or (cp >= 0X2_A_7_0_0 and cp <= 0X2_B_7_3_F) # or (cp >= 0X2_B_7_4_0 and cp <= 0X2_B_8_1_F) # or (cp >= 0X2_B_8_2_0 and cp <= 0X2_C_E_A_F) # or (cp >= 0XF_9_0_0 and cp <= 0XF_A_F_F) or (cp >= 0X2_F_8_0_0 and cp <= 0X2_F_A_1_F) # ): # return True return False def _snake_case ( lowerCAmelCase : str ): """simple docstring""" for char in word: SCREAMING_SNAKE_CASE_ : Any = ord(lowerCAmelCase ) if not _is_chinese_char(lowerCAmelCase ): return 0 return 1 def _snake_case ( lowerCAmelCase : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = set() for token in tokens: SCREAMING_SNAKE_CASE_ : int = len(lowerCAmelCase ) > 1 and is_chinese(lowerCAmelCase ) if chinese_word: word_set.add(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(lowerCAmelCase ) return word_list def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens SCREAMING_SNAKE_CASE_ : str = max([len(lowerCAmelCase ) for w in chinese_word_set] ) SCREAMING_SNAKE_CASE_ : int = bert_tokens SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = 0, len(lowerCAmelCase ) while start < end: SCREAMING_SNAKE_CASE_ : Optional[int] = True if is_chinese(bert_word[start] ): SCREAMING_SNAKE_CASE_ : List[str] = min(end - start , lowerCAmelCase ) for i in range(lowerCAmelCase , 1 , -1 ): SCREAMING_SNAKE_CASE_ : Tuple = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): SCREAMING_SNAKE_CASE_ : Optional[int] = "##" + bert_word[j] SCREAMING_SNAKE_CASE_ : int = start + i SCREAMING_SNAKE_CASE_ : Optional[Any] = False break if single_word: start += 1 return bert_word def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : LTP , lowerCAmelCase : BertTokenizer ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : Optional[int] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] SCREAMING_SNAKE_CASE_ : List[Any] = [get_chinese_word(lowerCAmelCase ) for r in res] ltp_res.extend(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : str = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=lowerCAmelCase , truncation=lowerCAmelCase , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : int = [] for input_ids, chinese_word in zip(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : str = [] for id in input_ids: SCREAMING_SNAKE_CASE_ : Tuple = bert_tokenizer._convert_id_to_token(lowerCAmelCase ) input_tokens.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Any = add_sub_symbol(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(lowerCAmelCase ): if token[:2] == "##": SCREAMING_SNAKE_CASE_ : List[Any] = token[2:] # save chinese tokens' pos if len(lowerCAmelCase ) == 1 and _is_chinese_char(ord(lowerCAmelCase ) ): ref_id.append(lowerCAmelCase ) ref_ids.append(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) return ref_ids def _snake_case ( lowerCAmelCase : Optional[int] ): """simple docstring""" with open(args.file_name , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : List[Any] = f.readlines() SCREAMING_SNAKE_CASE_ : int = [line.strip() for line in data if len(lowerCAmelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LTP(args.ltp ) # faster in GPU device SCREAMING_SNAKE_CASE_ : Tuple = BertTokenizer.from_pretrained(args.bert ) SCREAMING_SNAKE_CASE_ : List[str] = prepare_ref(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) with open(args.save_path , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : Optional[int] = [json.dumps(lowerCAmelCase ) + "\n" for ref in ref_ids] f.writelines(lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase : Any = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') __lowerCamelCase : int = parser.parse_args() main(args)
18
'''simple docstring''' # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int ): with open(_SCREAMING_SNAKE_CASE , 'r' ) as fh: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_EX ) try: print(*_SCREAMING_SNAKE_CASE ) finally: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) __lowercase : Dict = int(os.environ['LOCAL_RANK']) torch.cuda.set_device(local_rank) __lowercase : Tuple = torch.device('cuda', local_rank) __lowercase : Optional[int] = socket.gethostname() __lowercase : List[str] = f'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group('nccl') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __lowercase : str = dist.get_rank() __lowercase : Union[str, Any] = dist.get_world_size() printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(f'''{gpu} is broken''') raise
27
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __A ={ '''configuration_mobilebert''': [ '''MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileBertConfig''', '''MobileBertOnnxConfig''', ], '''tokenization_mobilebert''': ['''MobileBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =['''MobileBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileBertForMaskedLM''', '''MobileBertForMultipleChoice''', '''MobileBertForNextSentencePrediction''', '''MobileBertForPreTraining''', '''MobileBertForQuestionAnswering''', '''MobileBertForSequenceClassification''', '''MobileBertForTokenClassification''', '''MobileBertLayer''', '''MobileBertModel''', '''MobileBertPreTrainedModel''', '''load_tf_weights_in_mobilebert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileBertForMaskedLM''', '''TFMobileBertForMultipleChoice''', '''TFMobileBertForNextSentencePrediction''', '''TFMobileBertForPreTraining''', '''TFMobileBertForQuestionAnswering''', '''TFMobileBertForSequenceClassification''', '''TFMobileBertForTokenClassification''', '''TFMobileBertMainLayer''', '''TFMobileBertModel''', '''TFMobileBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys __A =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase : str = { '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: __lowercase : str = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] __lowercase : Tuple = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] __lowercase : Dict = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): __lowercase : Optional[Any] = [ '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 __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class __snake_case : def __init__( self ,snake_case ,snake_case=13 ,snake_case=7 ,snake_case=True ,snake_case=True ,snake_case=True ,snake_case=99 ,snake_case=32 ,snake_case=5 ,snake_case=4 ,snake_case=37 ,snake_case="gelu" ,snake_case=0.1 ,snake_case=0.1 ,snake_case=512 ,snake_case=16 ,snake_case=2 ,snake_case=0.02 ,snake_case=3 ,snake_case=4 ,snake_case=None ,): '''simple docstring''' lowercase : str = parent lowercase : List[str] = batch_size lowercase : Dict = seq_length lowercase : Tuple = is_training lowercase : Any = use_token_type_ids lowercase : str = use_labels lowercase : List[str] = vocab_size lowercase : Union[str, Any] = hidden_size lowercase : Union[str, Any] = num_hidden_layers lowercase : Optional[Any] = num_attention_heads lowercase : Tuple = intermediate_size lowercase : Any = hidden_act lowercase : Any = hidden_dropout_prob lowercase : Optional[int] = attention_probs_dropout_prob lowercase : Optional[int] = max_position_embeddings lowercase : str = type_vocab_size lowercase : Tuple = type_sequence_label_size lowercase : Union[str, Any] = initializer_range lowercase : List[str] = num_labels lowercase : Any = num_choices lowercase : Optional[int] = scope lowercase : Dict = self.vocab_size - 1 def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowercase : Optional[Any] = None if self.use_token_type_ids: lowercase : int = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) lowercase : Any = None lowercase : Dict = None lowercase : Any = None if self.use_labels: lowercase : Optional[int] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowercase : List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) lowercase : Union[str, Any] = ids_tensor([self.batch_size] ,self.num_choices ) lowercase : List[str] = OpenAIGPTConfig( 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 ,pad_token_id=self.pad_token_id ,) lowercase : str = ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,*snake_case ): '''simple docstring''' lowercase : int = OpenAIGPTModel(config=snake_case ) model.to(snake_case ) model.eval() lowercase : Dict = model(snake_case ,token_type_ids=snake_case ,head_mask=snake_case ) lowercase : Union[str, Any] = model(snake_case ,token_type_ids=snake_case ) lowercase : int = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,*snake_case ): '''simple docstring''' lowercase : List[Any] = OpenAIGPTLMHeadModel(snake_case ) model.to(snake_case ) model.eval() lowercase : Dict = model(snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,*snake_case ): '''simple docstring''' lowercase : List[Any] = OpenAIGPTDoubleHeadsModel(snake_case ) model.to(snake_case ) model.eval() lowercase : int = model(snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,*snake_case ): '''simple docstring''' lowercase : List[Any] = self.num_labels lowercase : Any = OpenAIGPTForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() lowercase : int = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowercase : List[str] = model(snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) : Any = config_and_inputs lowercase : int = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask, } return config, inputs_dict @require_torch class __snake_case ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): _a : Optional[Any]= ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) _a : int= ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly _a : str= ( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case=False ): '''simple docstring''' lowercase : Tuple = super()._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": lowercase : List[str] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) ,dtype=torch.long ,device=snake_case ,) lowercase : Tuple = inputs_dict["""labels"""] lowercase : Dict = inputs_dict["""labels"""] lowercase : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) ,dtype=torch.long ,device=snake_case ,) lowercase : List[str] = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=snake_case ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = OpenAIGPTModelTester(self ) lowercase : str = ConfigTester(self ,config_class=snake_case ,n_embd=37 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*snake_case ) @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : Any = OpenAIGPTModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_torch class __snake_case ( unittest.TestCase ): @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt""" ) model.to(snake_case ) lowercase : List[Any] = torch.tensor([[481, 4735, 544]] ,dtype=torch.long ,device=snake_case ) # the president is lowercase : str = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the lowercase : int = model.generate(snake_case ,do_sample=snake_case ) self.assertListEqual(output_ids[0].tolist() ,snake_case )
20
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration __lowercase : Tuple = pytest.mark.integration __lowercase : Optional[int] = {'comet'} __lowercase : List[str] = importlib.util.find_spec('fairseq') is not None __lowercase : str = {'code_eval'} __lowercase : List[Any] = os.name == 'nt' __lowercase : Optional[Any] = {'bertscore', 'frugalscore', 'perplexity'} __lowercase : Optional[Any] = importlib.util.find_spec('transformers') is not None def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : int , _SCREAMING_SNAKE_CASE : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (): __a : List[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) @local class __UpperCamelCase ( parameterized.TestCase ): A_ = {} A_ = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = '[...]' __a : Tuple = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) __a : Optional[Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=__a ) # check parameters __a : Dict = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__a , metric_module.__name__ ): with self.use_local_metrics(): try: __a : str = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = '[...]' __a : Optional[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) # run doctest with self.use_local_metrics(): __a : List[Any] = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__a ): yield else: yield @contextmanager def __UpperCAmelCase ( self ): '''simple docstring''' def load_local_metric(__a , *__a , **__a ): return load_metric(os.path.join('metrics' , __a ) , *__a , **__a ) with patch('datasets.load_metric' ) as mock_load_metric: __a : Dict = load_local_metric yield @classmethod def __UpperCAmelCase ( cls , __a ): '''simple docstring''' def wrapper(__a ): __a : Optional[Any] = contextmanager(__a ) __a : str = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self , __a ): '''simple docstring''' assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: __a : Dict = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): import torch def bert_cos_score_idf(_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , *_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Optional[int] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: __a : str = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): def load_from_checkpoint(_SCREAMING_SNAKE_CASE : Optional[int] ): class __UpperCamelCase : def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' assert len(__a ) == 2 __a : Dict = [0.19, 0.92] return scores, sum(__a ) / len(__a ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: __a : str = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: __a : int = load_from_checkpoint yield def lowerCamelCase (): __a : Optional[Any] = load_metric(os.path.join('metrics' , 'seqeval' ) ) __a : List[str] = 'ERROR' __a : List[str] = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): metric.compute(predictions=[] , references=[] , scheme=_SCREAMING_SNAKE_CASE )
27
0
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('dataset_size' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('input_in_memory_max_size' , ['default', 0, 100 * 2**20, 900 * 2**20] ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> int: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , 'IN_MEMORY_MAX_SIZE' , lowerCamelCase_ ) _lowercase : List[Any] = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: _lowercase : Tuple = dataset_size < in_memory_max_size else: _lowercase : Any = False _lowercase : Union[str, Any] = is_small_dataset(lowerCamelCase_ ) assert result == expected
21
'''simple docstring''' import re import string import numpy as np import datasets __lowercase : Tuple = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' __lowercase : List[str] = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' __lowercase : Any = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def __UpperCAmelCase ( 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' ), } ) , reference_urls=[] , ) def __UpperCAmelCase ( self , __a , __a , __a=None , __a=False , __a=False , __a=False , ): '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: __a : Tuple = np.array([re.sub(__a , '' , __a ) for x in predictions] ) __a : List[Any] = np.array([re.sub(__a , '' , __a ) for x in references] ) else: __a : int = np.asarray(__a ) __a : str = np.asarray(__a ) if ignore_case: __a : Dict = np.char.lower(__a ) __a : List[str] = np.char.lower(__a ) if ignore_punctuation: __a : Dict = string.punctuation.maketrans('' , '' , string.punctuation ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Dict = np.char.translate(__a , table=__a ) if ignore_numbers: __a : Optional[int] = string.digits.maketrans('' , '' , string.digits ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Optional[int] = np.char.translate(__a , table=__a ) __a : Any = predictions == references return {"exact_match": np.mean(__a ) * 100}
27
0
'''simple docstring''' import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class A_ ( lowerCAmelCase_ , unittest.TestCase ): _lowerCamelCase : str = CanineTokenizer _lowerCamelCase : Tuple = False def lowercase ( self : List[Any] ): super().setUp() _UpperCAmelCase = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowercase ( self : List[str] ): return CanineTokenizer.from_pretrained("google/canine-s" ) def lowercase ( self : Union[str, Any] , **snake_case_ : List[Any] ): _UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname , **snake_case_ ) _UpperCAmelCase = 1_0_2_4 return tokenizer @require_torch def lowercase ( self : List[str] ): _UpperCAmelCase = self.canine_tokenizer _UpperCAmelCase = ["Life is like a box of chocolates.", "You never know what you're gonna get."] # fmt: off _UpperCAmelCase = [5_7_3_4_4, 7_6, 1_0_5, 1_0_2, 1_0_1, 3_2, 1_0_5, 1_1_5, 3_2, 1_0_8, 1_0_5, 1_0_7, 1_0_1, 3_2, 9_7, 3_2, 9_8, 1_1_1, 1_2_0, 3_2, 1_1_1, 1_0_2, 3_2, 9_9, 1_0_4, 1_1_1, 9_9, 1_1_1, 1_0_8, 9_7, 1_1_6, 1_0_1, 1_1_5, 4_6, 5_7_3_4_5, 0, 0, 0, 0] # fmt: on _UpperCAmelCase = tokenizer(snake_case_ , padding=snake_case_ , return_tensors="pt" ) self.assertIsInstance(snake_case_ , snake_case_ ) _UpperCAmelCase = list(batch.input_ids.numpy()[0] ) self.assertListEqual(snake_case_ , snake_case_ ) self.assertEqual((2, 3_9) , batch.input_ids.shape ) self.assertEqual((2, 3_9) , batch.attention_mask.shape ) @require_torch def lowercase ( self : List[Any] ): _UpperCAmelCase = self.canine_tokenizer _UpperCAmelCase = ["Once there was a man.", "He wrote a test in HuggingFace Tranformers."] _UpperCAmelCase = tokenizer(snake_case_ , padding=snake_case_ , return_tensors="pt" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("input_ids" , snake_case_ ) self.assertIn("attention_mask" , snake_case_ ) self.assertIn("token_type_ids" , snake_case_ ) @require_torch def lowercase ( self : Optional[int] ): _UpperCAmelCase = self.canine_tokenizer _UpperCAmelCase = [ "What's the weater?", "It's about 25 degrees.", ] _UpperCAmelCase = tokenizer( text_target=snake_case_ , max_length=3_2 , padding="max_length" , truncation=snake_case_ , return_tensors="pt" ) self.assertEqual(3_2 , targets["input_ids"].shape[1] ) def lowercase ( self : Union[str, Any] ): # safety check on max_len default value so we are sure the test works _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = " He is very happy, UNwant\u00E9d,running" _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) tokenizer.save_pretrained(snake_case_ ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(snake_case_ ) _UpperCAmelCase = after_tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) shutil.rmtree(snake_case_ ) _UpperCAmelCase = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = " He is very happy, UNwant\u00E9d,running" _UpperCAmelCase = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: _UpperCAmelCase = chr(0Xe0_07 ) additional_special_tokens.append(snake_case_ ) tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) tokenizer.save_pretrained(snake_case_ ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(snake_case_ ) _UpperCAmelCase = after_tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) self.assertIn(snake_case_ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(snake_case_ , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(snake_case_ ) def lowercase ( self : int ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase , _UpperCAmelCase = self.get_clean_sequence(snake_case_ ) # a special token for Canine can be defined as follows: _UpperCAmelCase = 0Xe0_05 _UpperCAmelCase = chr(snake_case_ ) tokenizer.add_special_tokens({"cls_token": special_token} ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertEqual(len(snake_case_ ) , 1 ) _UpperCAmelCase = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertEqual(snake_case_ , input_encoded + special_token_id ) _UpperCAmelCase = tokenizer.decode(snake_case_ , skip_special_tokens=snake_case_ ) self.assertTrue(special_token not in decoded ) def lowercase ( self : int ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase = chr(0Xe0_05 ) _UpperCAmelCase = chr(0Xe0_06 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=snake_case_ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]} ) _UpperCAmelCase = tokenizer.tokenize(snake_case_ ) _UpperCAmelCase = tokenizer.tokenize(snake_case_ ) self.assertEqual(len(snake_case_ ) , 1 ) self.assertEqual(len(snake_case_ ) , 1 ) self.assertEqual(token_a[0] , snake_case_ ) self.assertEqual(token_a[0] , snake_case_ ) @require_tokenizers def lowercase ( self : Any ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: _UpperCAmelCase = 0Xe0_06 _UpperCAmelCase = chr(snake_case_ ) _UpperCAmelCase = AddedToken(snake_case_ , lstrip=snake_case_ ) tokenizer.add_special_tokens({"additional_special_tokens": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(snake_case_ ) tokenizer.from_pretrained(snake_case_ ) def lowercase ( self : List[Any] ): _UpperCAmelCase = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(snake_case_ ) with open(os.path.join(snake_case_ , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file: _UpperCAmelCase = json.load(snake_case_ ) with open(os.path.join(snake_case_ , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file: _UpperCAmelCase = json.load(snake_case_ ) # a special token for Canine can be defined as follows: _UpperCAmelCase = 0Xe0_06 _UpperCAmelCase = chr(snake_case_ ) _UpperCAmelCase = [new_token_a] _UpperCAmelCase = [new_token_a] with open(os.path.join(snake_case_ , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(snake_case_ , snake_case_ ) with open(os.path.join(snake_case_ , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(snake_case_ , snake_case_ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files _UpperCAmelCase = tokenizer_class.from_pretrained(snake_case_ , extra_ids=0 ) self.assertIn(snake_case_ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) _UpperCAmelCase = 0Xe0_07 _UpperCAmelCase = chr(snake_case_ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained _UpperCAmelCase = [AddedToken(snake_case_ , lstrip=snake_case_ )] _UpperCAmelCase = tokenizer_class.from_pretrained( snake_case_ , additional_special_tokens=snake_case_ , extra_ids=0 ) self.assertIn(snake_case_ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowercase ( self : Tuple ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase = "hello world" if self.space_between_special_tokens: _UpperCAmelCase = "[CLS] hello world [SEP]" else: _UpperCAmelCase = input _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.decode(snake_case_ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(snake_case_ , [output, output.lower()] ) def lowercase ( self : str ): _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", ] _UpperCAmelCase = "a" _UpperCAmelCase = ord(snake_case_ ) for attr in attributes_list: setattr(snake_case_ , attr + "_id" , snake_case_ ) self.assertEqual(getattr(snake_case_ , snake_case_ ) , snake_case_ ) self.assertEqual(getattr(snake_case_ , attr + "_id" ) , snake_case_ ) setattr(snake_case_ , attr + "_id" , snake_case_ ) self.assertEqual(getattr(snake_case_ , snake_case_ ) , snake_case_ ) self.assertEqual(getattr(snake_case_ , attr + "_id" ) , snake_case_ ) setattr(snake_case_ , "additional_special_tokens_ids" , [] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens" ) , [] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens_ids" ) , [] ) _UpperCAmelCase = 0Xe0_06 _UpperCAmelCase = chr(snake_case_ ) setattr(snake_case_ , "additional_special_tokens_ids" , [additional_special_token_id] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens" ) , [additional_special_token] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens_ids" ) , [additional_special_token_id] ) def lowercase ( self : Any ): pass def lowercase ( self : List[Any] ): pass def lowercase ( self : Union[str, Any] ): pass def lowercase ( self : List[Any] ): pass def lowercase ( self : List[Any] ): pass def lowercase ( self : int ): pass def lowercase ( self : int ): pass def lowercase ( self : Optional[Any] ): pass
22
'''simple docstring''' import os import sys __lowercase : List[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowercase : int = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[str] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoConfig.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoTokenizer.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : str , **_SCREAMING_SNAKE_CASE : Any ): return AutoTokenizer.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModel.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Union[str, Any] ): return AutoModel.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[Any] , **_SCREAMING_SNAKE_CASE : Optional[int] ): return AutoModelForCausalLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Union[str, Any] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoModelForMaskedLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Optional[Any] , **_SCREAMING_SNAKE_CASE : Any ): return AutoModelForSequenceClassification.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Any , **_SCREAMING_SNAKE_CASE : List[str] ): return AutoModelForQuestionAnswering.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
27
0
'''simple docstring''' from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging UpperCamelCase__: str = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE: """simple docstring""" lowerCamelCase__ = 42 lowerCamelCase__ = None @staticmethod def A ( ) -> Optional[Any]: raise NotImplementedError def A ( self : Dict , __snake_case : Union[str, Any] , __snake_case : int , __snake_case : str , **__snake_case : str ) -> Optional[int]: raise NotImplementedError def A ( self : Union[str, Any] , __snake_case : str ) -> Union[str, Any]: raise NotImplementedError def A ( self : List[Any] ) -> List[Any]: if not self.is_available(): raise RuntimeError( F"""You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.""" ) @classmethod def A ( cls : List[Any] ) -> List[Any]: return F"""`pip install {cls.pip_package or cls.name}`""" class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = """optuna""" @staticmethod def A ( ) -> str: return is_optuna_available() def A ( self : Optional[int] , __snake_case : Tuple , __snake_case : int , __snake_case : str , **__snake_case : Tuple ) -> Dict: return run_hp_search_optuna(__snake_case , __snake_case , __snake_case , **__snake_case ) def A ( self : Union[str, Any] , __snake_case : str ) -> str: return default_hp_space_optuna(__snake_case ) class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = """ray""" lowerCamelCase__ = """'ray[tune]'""" @staticmethod def A ( ) -> str: return is_ray_available() def A ( self : Union[str, Any] , __snake_case : Any , __snake_case : int , __snake_case : str , **__snake_case : Optional[int] ) -> List[Any]: return run_hp_search_ray(__snake_case , __snake_case , __snake_case , **__snake_case ) def A ( self : List[str] , __snake_case : List[Any] ) -> List[Any]: return default_hp_space_ray(__snake_case ) class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = """sigopt""" @staticmethod def A ( ) -> List[str]: return is_sigopt_available() def A ( self : Optional[Any] , __snake_case : Optional[Any] , __snake_case : int , __snake_case : str , **__snake_case : Union[str, Any] ) -> Tuple: return run_hp_search_sigopt(__snake_case , __snake_case , __snake_case , **__snake_case ) def A ( self : int , __snake_case : Optional[Any] ) -> Any: return default_hp_space_sigopt(__snake_case ) class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = """wandb""" @staticmethod def A ( ) -> Tuple: return is_wandb_available() def A ( self : Any , __snake_case : List[Any] , __snake_case : int , __snake_case : str , **__snake_case : Tuple ) -> Optional[Any]: return run_hp_search_wandb(__snake_case , __snake_case , __snake_case , **__snake_case ) def A ( self : str , __snake_case : str ) -> int: return default_hp_space_wandb(__snake_case ) UpperCamelCase__: Optional[int] = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def snake_case_ ( ) -> str: UpperCAmelCase : int = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(_lowerCAmelCase ) > 0: UpperCAmelCase : Union[str, Any] = available_backends[0].name if len(_lowerCAmelCase ) > 1: logger.info( f"""{len(_lowerCAmelCase )} hyperparameter search backends available. Using {name} as the default.""" ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( f""" - To install {backend.name} run {backend.pip_install()}""" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
23
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = inspect.getfile(accelerate.test_utils ) __a : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __a : Union[str, Any] = test_metrics @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def __UpperCAmelCase ( self ): '''simple docstring''' self.test_metrics.main() @require_multi_gpu def __UpperCAmelCase ( self ): '''simple docstring''' print(f"""Found {torch.cuda.device_count()} devices.""" ) __a : List[Any] = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() )
27
0
import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): A_ : Union[str, Any] = ComputeEnvironment.AMAZON_SAGEMAKER A_ : List[Any] = True A_ : Tuple = 'ml.p3.2xlarge' A_ : Union[str, Any] = 'accelerate_sagemaker_execution_role' A_ : str = 'hf-sm' A_ : str = 'us-east-1' A_ : Tuple = 1 A_ : int = 'accelerate-sagemaker-1' A_ : Union[str, Any] = '1.6' A_ : Tuple = '4.4' A_ : Optional[Any] = 'train.py' A_ : Optional[Any] = [ '--model_name_or_path', 'bert', '--do_train', 'False', '--epochs', '3', '--learning_rate', '5e-5', '--max_steps', '50.5', ] A_ : Dict = [ '--model_name_or_path', 'bert', '--do_train', '--do_test', 'False', '--do_predict', '--epochs', '3', '--learning_rate', '5e-5', '--max_steps', '50.5', ] class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def a (self : Dict ): """simple docstring""" __snake_case = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args ) assert isinstance(converted_args['''model_name_or_path'''] , a__ ) assert isinstance(converted_args['''do_train'''] , a__ ) assert isinstance(converted_args['''epochs'''] , a__ ) assert isinstance(converted_args['''learning_rate'''] , a__ ) assert isinstance(converted_args['''max_steps'''] , a__ ) with pytest.raises(a__ ): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args )
24
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): __a : Optional[Any] = tmp_path / 'file.csv' __a : Union[str, Any] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : str = tmp_path / 'malformed_file.csv' __a : int = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = tmp_path / 'csv_with_image.csv' __a : Dict = textwrap.dedent( F"""\ image {image_file} """ ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Union[str, Any] = tmp_path / 'csv_with_label.csv' __a : Any = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Dict = tmp_path / 'csv_with_int_list.csv' __a : Tuple = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): __a : int = Csv() __a : str = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_SCREAMING_SNAKE_CASE , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(_SCREAMING_SNAKE_CASE ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1] __a : Tuple = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) __a : Any = csv._generate_tables([[csv_file_with_image]] ) __a : int = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() __a : Any = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1:] __a : Optional[int] = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) __a : List[str] = csv._generate_tables([[csv_file_with_label]] ) __a : Dict = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() __a : int = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(_SCREAMING_SNAKE_CASE ) for label in labels] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda _SCREAMING_SNAKE_CASE : [int(_SCREAMING_SNAKE_CASE ) for i in x.split()]} ) __a : Any = csv._generate_tables([[csv_file_with_int_list]] ) __a : Any = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) __a : Tuple = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
27
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin UpperCAmelCase__ : Tuple = random.Random() if is_torch_available(): import torch def lowercase_ ( _snake_case ,_snake_case=1.0 ,_snake_case=None ,_snake_case=None ): if rng is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = global_rng SCREAMING_SNAKE_CASE__ : List[str] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class lowerCAmelCase_ (unittest.TestCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=4_00 , SCREAMING_SNAKE_CASE__=20_00 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=1_60_00 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : Dict = min_seq_length SCREAMING_SNAKE_CASE__ : List[str] = max_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feature_size SCREAMING_SNAKE_CASE__ : Optional[Any] = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[Any] = return_attention_mask SCREAMING_SNAKE_CASE__ : List[Any] = do_normalize def __magic_name__ (self ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __magic_name__ (self , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False ) -> List[Any]: """simple docstring""" def _flatten(SCREAMING_SNAKE_CASE__ ): return list(itertools.chain(*SCREAMING_SNAKE_CASE__ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : int = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : str = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase_ (a__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase : List[str] = ASTFeatureExtractor def __magic_name__ (self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ASTFeatureExtractionTester(self ) def __magic_name__ (self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : int = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors="""np""" ).input_values SCREAMING_SNAKE_CASE__ : str = feat_extract(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] SCREAMING_SNAKE_CASE__ : Optional[int] = np.asarray(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(SCREAMING_SNAKE_CASE__ , return_tensors="""np""" ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(SCREAMING_SNAKE_CASE__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) ) @require_torch def __magic_name__ (self ) -> Tuple: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Any = np.random.rand(1_00 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Dict = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : Union[str, Any] = ds.sort("""id""" ).select(range(SCREAMING_SNAKE_CASE__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] @require_torch def __magic_name__ (self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776, -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133, -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936, -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[int] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = ASTFeatureExtractor() SCREAMING_SNAKE_CASE__ : Dict = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
25
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Union[str, Any] = { 'configuration_blenderbot': [ 'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotConfig', 'BlenderbotOnnxConfig', ], 'tokenization_blenderbot': ['BlenderbotTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ['BlenderbotTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = [ 'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotForCausalLM', 'BlenderbotForConditionalGeneration', 'BlenderbotModel', 'BlenderbotPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ 'TFBlenderbotForConditionalGeneration', 'TFBlenderbotModel', 'TFBlenderbotPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Dict = [ 'FlaxBlenderbotForConditionalGeneration', 'FlaxBlenderbotModel', 'FlaxBlenderbotPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
import torch from diffusers import DiffusionPipeline class lowercase ( UpperCamelCase__ ): def __init__( self , _a , _a ) -> Optional[Any]: super().__init__() self.register_modules(unet=_a , scheduler=_a ) def __call__( self ) -> Dict: _A : str = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) _A : Any = 1 _A : List[Any] = self.unet(_a , _a ).sample _A : Dict = self.scheduler.step(_a , _a , _a ).prev_sample _A : int = scheduler_output - scheduler_output + torch.ones_like(_a ) return result
26
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase : def __init__( self , __a , __a=2 , __a=3 , __a=4 , __a=2 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=36 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=6 , __a=6 , __a=3 , __a=4 , __a=None , __a=1000 , ): '''simple docstring''' __a : Optional[Any] = parent __a : int = batch_size __a : Any = num_channels __a : Optional[int] = image_size __a : Dict = patch_size __a : int = is_training __a : Union[str, Any] = use_input_mask __a : Optional[int] = use_token_type_ids __a : Dict = use_labels __a : str = vocab_size __a : List[Any] = hidden_size __a : Union[str, Any] = num_hidden_layers __a : str = num_attention_heads __a : Union[str, Any] = intermediate_size __a : Any = hidden_act __a : List[str] = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : List[Any] = max_position_embeddings __a : Tuple = type_vocab_size __a : Any = type_sequence_label_size __a : Optional[int] = initializer_range __a : Any = coordinate_size __a : List[Any] = shape_size __a : Optional[int] = num_labels __a : Dict = num_choices __a : Union[str, Any] = scope __a : Union[str, Any] = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __a : Optional[int] = text_seq_length __a : Any = (image_size // patch_size) ** 2 + 1 __a : Dict = self.text_seq_length + self.image_seq_length def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __a : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __a : Any = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a : List[Any] = bbox[i, j, 3] __a : Tuple = bbox[i, j, 1] __a : str = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __a : int = bbox[i, j, 2] __a : Dict = bbox[i, j, 0] __a : int = tmp_coordinate __a : Optional[int] = tf.constant(__a ) __a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_input_mask: __a : Optional[Any] = random_attention_mask([self.batch_size, self.text_seq_length] ) __a : str = None if self.use_token_type_ids: __a : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __a : Optional[Any] = None __a : Optional[int] = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __a : int = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = TFLayoutLMvaModel(config=__a ) # text + image __a : List[Any] = model(__a , pixel_values=__a , training=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , training=__a , ) __a : Optional[int] = model(__a , bbox=__a , pixel_values=__a , training=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __a : Any = model(__a , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __a : str = model({'pixel_values': pixel_values} , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = TFLayoutLMvaForSequenceClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : str = self.num_labels __a : Optional[Any] = TFLayoutLMvaForTokenClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[Any] = 2 __a : Any = TFLayoutLMvaForQuestionAnswering(config=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , training=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a)) : Dict = config_and_inputs __a : Any = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) A_ = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) A_ = False A_ = False A_ = False def __UpperCAmelCase ( self , __a , __a , __a , __a , __a ): '''simple docstring''' return True def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : str = copy.deepcopy(__a ) if model_class in get_values(__a ): __a : str = { k: tf.tile(tf.expand_dims(__a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(__a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__a ): __a : Optional[int] = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : int = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __a : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Union[str, Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = TFLayoutLMvaModelTester(self ) __a : Optional[int] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) if getattr(__a , 'hf_compute_loss' , __a ): # The number of elements in the loss should be the same as the number of elements in the label __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=__a )[0] ] __a : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : Dict = prepared_for_class.pop('input_ids' ) __a : Tuple = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __a : Union[str, Any] = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __a : List[Any] = -100 __a : List[str] = tf.convert_to_tensor(__a ) __a : Any = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = model(__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __a : Tuple = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) # Get keys that were added with the _prepare_for_class function __a : Dict = prepared_for_class.keys() - inputs_dict.keys() __a : Any = inspect.signature(model.call ).parameters __a : str = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __a : List[Any] = {0: 'input_ids'} for label_key in label_keys: __a : List[Any] = signature_names.index(__a ) __a : Union[str, Any] = label_key __a : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __a : Union[str, Any] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __a : Optional[Any] = prepared_for_class[value] __a : str = tuple(__a ) # Send to model __a : Tuple = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a : Any = type self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( __a , __a , __a , __a , __a , __a , __a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = TFLayoutLMvaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__a ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __a : Tuple = self.default_image_processor __a : List[Any] = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ).pixel_values __a : Union[str, Any] = tf.constant([[1, 2]] ) __a : Optional[Any] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __a : Tuple = model(input_ids=__a , bbox=__a , pixel_values=__a , training=__a ) # verify the logits __a : List[Any] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , __a ) __a : Optional[Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , __a , atol=1E-4 ) )
27
0
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin _lowerCamelCase : Tuple = random.Random() def __lowerCamelCase ( A__ , A__=1.0 , A__=None , A__=None ) -> Union[str, Any]: """simple docstring""" if rng is None: UpperCamelCase = global_rng UpperCamelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any]=7 , UpperCamelCase__ : List[str]=4_0_0 , UpperCamelCase__ : str=2_0_0_0 , UpperCamelCase__ : Any=1 , UpperCamelCase__ : Optional[Any]=0.0 , UpperCamelCase__ : Tuple=1_6_0_0_0 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Dict=True , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = min_seq_length UpperCamelCase = max_seq_length UpperCamelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase = feature_size UpperCamelCase = padding_value UpperCamelCase = sampling_rate UpperCamelCase = return_attention_mask UpperCamelCase = do_normalize def A ( self : Optional[int] ): """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def A ( self : Union[str, Any] , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Union[str, Any]=False ): """simple docstring""" def _flatten(UpperCamelCase__ : Optional[Any] ): return list(itertools.chain(*UpperCamelCase__ ) ) if equal_length: UpperCamelCase = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase = [np.asarray(UpperCamelCase__ ) for x in speech_inputs] return speech_inputs class SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = WavaVecaFeatureExtractionTester(self ) def A ( self : Optional[Any] , UpperCamelCase__ : List[str] ): """simple docstring""" self.assertTrue(np.all(np.mean(UpperCamelCase__ , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(UpperCamelCase__ , axis=0 ) - 1 ) < 1E-3 ) ) def A ( self : Optional[int] ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = [np.asarray(UpperCamelCase__ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values UpperCamelCase = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-3 ) ) # Test batched UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(UpperCamelCase__ , UpperCamelCase__ ): self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] UpperCamelCase = np.asarray(UpperCamelCase__ ) UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(UpperCamelCase__ , UpperCamelCase__ ): self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-3 ) ) def A ( self : Dict ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = ['longest', 'max_length', 'do_not_pad'] UpperCamelCase = [None, 1_6_0_0, None] for max_length, padding in zip(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase = feat_extract(UpperCamelCase__ , padding=UpperCamelCase__ , max_length=UpperCamelCase__ , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def A ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = range(8_0_0 , 1_4_0_0 , 2_0_0 ) UpperCamelCase = [floats_list((1, x) )[0] for x in lengths] UpperCamelCase = ['longest', 'max_length', 'do_not_pad'] UpperCamelCase = [None, 1_6_0_0, None] for max_length, padding in zip(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase = feat_extract(UpperCamelCase__ , max_length=UpperCamelCase__ , padding=UpperCamelCase__ ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def A ( self : str ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = feat_extract( UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=1_0_0_0 , padding='max_length' , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def A ( self : Tuple ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = feat_extract( UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=1_0_0_0 , padding='longest' , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = feat_extract( UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=2_0_0_0 , padding='longest' , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) @require_torch def A ( self : Optional[Any] ): """simple docstring""" import torch UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = np.random.rand(1_0_0 ).astype(np.floataa ) UpperCamelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def A ( self : Any ): """simple docstring""" for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: UpperCamelCase = WavaVecaConfig.from_pretrained(UpperCamelCase__ ) UpperCamelCase = WavaVecaFeatureExtractor.from_pretrained(UpperCamelCase__ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == 'layer' )
28
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"""{test_file} instead.""" ) __a : Tuple = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __a : List[str] = components[:-1] + [test_fn.replace('.py' , '' )] __a : Optional[Any] = '.'.join(_SCREAMING_SNAKE_CASE ) return test_module_path def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = get_module_path(_SCREAMING_SNAKE_CASE ) __a : Dict = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = [] __a : List[str] = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : Any = [] __a : str = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): __a : int = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'all_model_classes' , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Tuple = test_class() if hasattr(_SCREAMING_SNAKE_CASE , 'setUp' ): test.setUp() __a : List[Any] = None if hasattr(_SCREAMING_SNAKE_CASE , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __a : List[str] = test.model_tester.__class__ return model_tester def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] ): __a : List[Any] = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [] for test_class in test_classes: __a : Any = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : str = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
27
0
def lowercase__ ( __snake_case : int , __snake_case : int , __snake_case : int ): '''simple docstring''' UpperCAmelCase_ : int = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowercase__ ( ): '''simple docstring''' print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
29
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = StableDiffusionInpaintPipeline A_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS A_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS A_ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess A_ = frozenset([] ) def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__a , ) __a : str = PNDMScheduler(skip_prk_steps=__a ) torch.manual_seed(0 ) __a : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __a : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __a : Dict = CLIPTextModel(__a ) __a : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __a : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCAmelCase ( self , __a , __a=0 ): '''simple docstring''' __a : Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) __a : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a : Tuple = Image.fromarray(np.uinta(__a ) ).convert('RGB' ).resize((64, 64) ) __a : Tuple = Image.fromarray(np.uinta(image + 4 ) ).convert('RGB' ).resize((64, 64) ) if str(__a ).startswith('mps' ): __a : Any = torch.manual_seed(__a ) else: __a : str = torch.Generator(device=__a ).manual_seed(__a ) __a : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': init_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator __a : str = self.get_dummy_components() __a : Union[str, Any] = StableDiffusionInpaintPipeline(**__a ) __a : List[Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) __a : List[Any] = self.get_dummy_inputs(__a ) __a : Dict = sd_pipe(**__a ).images __a : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : List[Any] = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench.npy' ) __a : Optional[int] = 'stabilityai/stable-diffusion-2-inpainting' __a : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained(__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Dict = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : int = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench_fp16.npy' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : List[str] = StableDiffusionInpaintPipeline.from_pretrained( __a , torch_dtype=torch.floataa , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Union[str, Any] = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : int = torch.manual_seed(0 ) __a : Optional[Any] = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : int = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def __UpperCAmelCase ( self ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __a : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : Any = PNDMScheduler.from_pretrained(__a , subfolder='scheduler' ) __a : str = StableDiffusionInpaintPipeline.from_pretrained( __a , safety_checker=__a , scheduler=__a , torch_dtype=torch.floataa , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __a : str = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : str = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , num_inference_steps=2 , output_type='np' , ) __a : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
27
0
import argparse from collections import defaultdict import yaml __a = 'docs/source/en/_toctree.yml' def a ( snake_case__: Dict ): '''simple docstring''' lowercase_ = defaultdict(snake_case__ ) for doc in model_doc: counts[doc["local"]] += 1 lowercase_ = [key for key, value in counts.items() if value > 1] lowercase_ = [] for duplicate_key in duplicates: lowercase_ = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(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(snake_case__ , key=lambda snake_case__ : s["title"].lower() ) def a ( snake_case__: List[Any]=False ): '''simple docstring''' with open(snake_case__ , encoding='''utf-8''' ) as f: lowercase_ = yaml.safe_load(f.read() ) # Get to the API doc lowercase_ = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowercase_ = content[api_idx]['''sections'''] # Then to the model doc lowercase_ = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 lowercase_ = api_doc[model_idx]['''sections'''] lowercase_ = [(idx, section) for idx, section in enumerate(snake_case__ ) if '''sections''' in section] lowercase_ = False for idx, modality_doc in modalities_docs: lowercase_ = modality_doc['''sections'''] lowercase_ = clean_model_doc_toc(snake_case__ ) if old_modality_doc != new_modality_doc: lowercase_ = True if overwrite: lowercase_ = new_modality_doc if diff: if overwrite: lowercase_ = model_doc lowercase_ = api_doc with open(snake_case__ , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(snake_case__ , allow_unicode=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)
30
'''simple docstring''' import requests __lowercase : Tuple = '' # <-- Put your OpenWeatherMap appid here! __lowercase : Tuple = 'https://api.openweathermap.org/data/2.5/' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Chicago" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'weather' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Kolkata, India" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : float = 5_5.6_8 , _SCREAMING_SNAKE_CASE : float = 1_2.5_7 , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowercase : Dict = input('Enter a location:').strip() if location: pprint(current_weather(location)) else: break
27
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' __UpperCamelCase: Optional[Any] = ["pixel_values"] def __init__( self : Optional[int] , A : bool = True , A : Dict[str, int] = None , A : float = None , A : PILImageResampling = PILImageResampling.BILINEAR , A : bool = True , A : Union[int, float] = 1 / 255 , A : bool = True , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , **A : int , ): super().__init__(**A ) _UpperCAmelCase : Optional[int] = size if size is not None else {"shortest_edge": 384} _UpperCAmelCase : Union[str, Any] = get_size_dict(A , default_to_square=A ) _UpperCAmelCase : int = do_resize _UpperCAmelCase : Optional[int] = size # Default value set here for backwards compatibility where the value in config is None _UpperCAmelCase : str = crop_pct if crop_pct is not None else 224 / 256 _UpperCAmelCase : Tuple = resample _UpperCAmelCase : Union[str, Any] = do_rescale _UpperCAmelCase : List[str] = rescale_factor _UpperCAmelCase : Tuple = do_normalize _UpperCAmelCase : Optional[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _UpperCAmelCase : Optional[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self : List[Any] , A : np.ndarray , A : Dict[str, int] , A : float , A : PILImageResampling = PILImageResampling.BICUBIC , A : Optional[Union[str, ChannelDimension]] = None , **A : Any , ): _UpperCAmelCase : Optional[int] = get_size_dict(A , default_to_square=A ) if "shortest_edge" not in size: raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""" ) _UpperCAmelCase : Optional[Any] = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct _UpperCAmelCase : Dict = int(shortest_edge / crop_pct ) _UpperCAmelCase : Optional[Any] = get_resize_output_image_size(A , size=A , default_to_square=A ) _UpperCAmelCase : int = resize(image=A , size=A , resample=A , data_format=A , **A ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=A , size=(shortest_edge, shortest_edge) , data_format=A , **A ) else: # warping (no cropping) when evaluated at 384 or larger return resize( A , size=(shortest_edge, shortest_edge) , resample=A , data_format=A , **A ) def _A ( self : Dict , A : np.ndarray , A : Union[int, float] , A : Optional[Union[str, ChannelDimension]] = None , **A : int , ): return rescale(A , scale=A , data_format=A , **A ) def _A ( self : List[Any] , A : np.ndarray , A : Union[float, List[float]] , A : Union[float, List[float]] , A : Optional[Union[str, ChannelDimension]] = None , **A : Optional[int] , ): return normalize(A , mean=A , std=A , data_format=A , **A ) def _A ( self : str , A : ImageInput , A : bool = None , A : Dict[str, int] = None , A : float = None , A : PILImageResampling = None , A : bool = None , A : float = None , A : bool = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[str, TensorType]] = None , A : ChannelDimension = ChannelDimension.FIRST , **A : List[Any] , ): _UpperCAmelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase : str = crop_pct if crop_pct is not None else self.crop_pct _UpperCAmelCase : Dict = resample if resample is not None else self.resample _UpperCAmelCase : List[Any] = do_rescale if do_rescale is not None else self.do_rescale _UpperCAmelCase : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCAmelCase : str = do_normalize if do_normalize is not None else self.do_normalize _UpperCAmelCase : Optional[int] = image_mean if image_mean is not None else self.image_mean _UpperCAmelCase : Dict = image_std if image_std is not None else self.image_std _UpperCAmelCase : Tuple = size if size is not None else self.size _UpperCAmelCase : List[str] = get_size_dict(A , default_to_square=A ) _UpperCAmelCase : Any = make_list_of_images(A ) if not valid_images(A ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. _UpperCAmelCase : List[Any] = [to_numpy_array(A ) for image in images] if do_resize: _UpperCAmelCase : List[Any] = [self.resize(image=A , size=A , crop_pct=A , resample=A ) for image in images] if do_rescale: _UpperCAmelCase : Any = [self.rescale(image=A , scale=A ) for image in images] if do_normalize: _UpperCAmelCase : Any = [self.normalize(image=A , mean=A , std=A ) for image in images] _UpperCAmelCase : Any = [to_channel_dimension_format(A , A ) for image in images] _UpperCAmelCase : Optional[Any] = {"pixel_values": images} return BatchFeature(data=A , tensor_type=A )
31
'''simple docstring''' import torch from transformers import AutoModel class __UpperCamelCase ( torch.nn.Module ): def __init__( self , __a="sayef/fsner-bert-base-uncased" ): '''simple docstring''' super(__a , self ).__init__() __a : Tuple = AutoModel.from_pretrained(__a , return_dict=__a ) __a : int = torch.nn.CosineSimilarity(3 , 1E-0_8 ) __a : Union[str, Any] = torch.nn.Softmax(dim=1 ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return self.bert(**__a ).last_hidden_state def __UpperCAmelCase ( self , __a ): '''simple docstring''' return token_embeddings.sum(2 , keepdim=__a ) def __UpperCAmelCase ( self , __a , __a , __a=1 ): '''simple docstring''' return self.softmax(T * self.cos(__a , __a ) ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : str = W_supports['sizes'].tolist() __a : Union[str, Any] = W_supports['start_token_id'].item() __a : Any = W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __a : Tuple = self.BERT(**__a ) __a : str = self.BERT(**__a ) __a : Any = None __a : Dict = None __a : Dict = W_supports['input_ids'] == start_token_id __a : Union[str, Any] = W_supports['input_ids'] == end_token_id for i, size in enumerate(__a ): if i == 0: __a : Optional[int] = 0 else: __a : Union[str, Any] = support_sizes[i - 1] __a : int = S[s : s + size][start_token_masks[s : s + size]] __a : Union[str, Any] = S[s : s + size][end_token_masks[s : s + size]] __a : Tuple = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __a : Dict = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __a : str = torch.vstack((p_starts, p_start) ) __a : str = torch.vstack((p_ends, p_end) ) else: __a : List[str] = p_start __a : int = p_end return p_starts, p_ends
27
0
import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser UpperCAmelCase_ : List[Any] = re.compile(R'\s+') def SCREAMING_SNAKE_CASE_ ( __A : Dict ) -> Optional[Any]: """simple docstring""" return {"hash": hashlib.mda(re.sub(__A , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> Dict: """simple docstring""" a_ : List[Any] = [len(__A ) for line in example['content'].splitlines()] return {"line_mean": np.mean(__A ), "line_max": max(__A )} def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> Optional[Any]: """simple docstring""" a_ : List[Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] , __A : Optional[int] ) -> Optional[int]: """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def SCREAMING_SNAKE_CASE_ ( __A : Optional[Any] , __A : int=5 ) -> Any: """simple docstring""" a_ : Dict = ['auto-generated', 'autogenerated', 'automatically generated'] a_ : Optional[int] = example['content'].splitlines() for _, line in zip(range(__A ) , __A ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def SCREAMING_SNAKE_CASE_ ( __A : Union[str, Any] , __A : Tuple=5 , __A : List[str]=0.05 ) -> List[Any]: """simple docstring""" a_ : List[Any] = ['unit tests', 'test file', 'configuration file'] a_ : Union[str, Any] = example['content'].splitlines() a_ : Union[str, Any] = 0 a_ : Optional[Any] = 0 # first test for _, line in zip(range(__A ) , __A ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test a_ : Optional[Any] = example['content'].count('\n' ) a_ : int = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def SCREAMING_SNAKE_CASE_ ( __A : str ) -> List[str]: """simple docstring""" a_ : str = ['def ', 'class ', 'for ', 'while '] a_ : Optional[Any] = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def SCREAMING_SNAKE_CASE_ ( __A : Any , __A : List[Any]=4 ) -> Optional[Any]: """simple docstring""" a_ : Any = example['content'].splitlines() a_ : List[Any] = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def SCREAMING_SNAKE_CASE_ ( __A : Optional[Any] ) -> List[str]: """simple docstring""" a_ : Optional[int] = tokenizer(example['content'] , truncation=__A )['input_ids'] a_ : Union[str, Any] = len(example['content'] ) / len(__A ) return {"ratio": ratio} def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] ) -> Optional[Any]: """simple docstring""" a_ : List[Any] = {} results.update(get_hash(__A ) ) results.update(line_stats(__A ) ) results.update(alpha_stats(__A ) ) results.update(char_token_ratio(__A ) ) results.update(is_autogenerated(__A ) ) results.update(is_config_or_test(__A ) ) results.update(has_no_keywords(__A ) ) results.update(has_few_assignments(__A ) ) return results def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str , __A : Union[str, Any] ) -> Optional[Any]: """simple docstring""" if not check_uniques(__A , __A ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> str: """simple docstring""" with open(__A , 'rb' ) as f_in: with gzip.open(str(__A ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(__A , __A ) os.unlink(__A ) # Settings UpperCAmelCase_ : Union[str, Any] = HfArgumentParser(PreprocessingArguments) UpperCAmelCase_ : Optional[Any] = parser.parse_args() if args.num_workers is None: UpperCAmelCase_ : Tuple = multiprocessing.cpu_count() UpperCAmelCase_ : Optional[Any] = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset UpperCAmelCase_ : List[str] = time.time() UpperCAmelCase_ : Union[str, Any] = load_dataset(args.dataset_name, split='train') print(F'Time to load dataset: {time.time()-t_start:.2f}') # Run preprocessing UpperCAmelCase_ : List[Any] = time.time() UpperCAmelCase_ : Optional[int] = ds.map(preprocess, num_proc=args.num_workers) print(F'Time to preprocess dataset: {time.time()-t_start:.2f}') # Deduplicate hashes UpperCAmelCase_ : int = set(ds.unique('hash')) UpperCAmelCase_ : List[str] = len(uniques) / len(ds) print(F'Fraction of duplicates: {1-frac:.2%}') # Deduplicate data and apply heuristics UpperCAmelCase_ : Optional[Any] = time.time() UpperCAmelCase_ : Optional[int] = ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args}) print(F'Time to filter dataset: {time.time()-t_start:.2f}') print(F'Size of filtered dataset: {len(ds_filter)}') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: UpperCAmelCase_ : Optional[int] = time.time() UpperCAmelCase_ , UpperCAmelCase_ : int = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'Time to deduplicate dataset: {time.time()-t_start:.2f}') print(F'Size of deduplicate dataset: {len(ds_filter)}') # Save data in batches of samples_per_file UpperCAmelCase_ : int = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / 'duplicate_clusters.json', 'w') as f: json.dump(duplicate_clusters, f) UpperCAmelCase_ : Dict = output_dir / 'data' data_dir.mkdir(exist_ok=True) UpperCAmelCase_ : int = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): UpperCAmelCase_ : List[Any] = str(data_dir / F'file-{file_number+1:012}.json') UpperCAmelCase_ : List[str] = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'Time to save dataset: {time.time()-t_start:.2f}')
32
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 35 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : Optional[Any] = x_den * y_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : Optional[int] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : List[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Any = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Optional[int] = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 __a : int = x_num * y_num __a : Optional[Any] = x_den * y_num + x_num * y_den __a : Tuple = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : List[Any] = x_num * x_num * y_num * y_num __a : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : Optional[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
27
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __A : List[str] = { '''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 : Optional[int] = ['''PerceiverFeatureExtractor'''] __A : List[Any] = ['''PerceiverImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = [ '''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 : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
33
'''simple docstring''' import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): @property def __UpperCAmelCase ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ort.SessionOptions() __a : Dict = False return options def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) __a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default __a : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__a , feature_extractor=__a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__a ) __a : Tuple = 'A red cat sitting on a park bench' __a : int = np.random.RandomState(0 ) __a : Tuple = pipe( prompt=__a , image=__a , mask_image=__a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=__a , output_type='np' , ) __a : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
27
0
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def snake_case_ (_a : Dict , _a : Optional[int] , _a : Dict , _a : Optional[Any] , _a : int ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file UpperCAmelCase = TapasConfig.from_json_file(_a ) # set absolute/relative position embeddings parameter UpperCAmelCase = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": UpperCAmelCase = TapasForQuestionAnswering(config=_a ) elif task == "WTQ": # run_task_main.py hparams UpperCAmelCase = 4 UpperCAmelCase = True # hparam_utils.py hparams UpperCAmelCase = 0.66_4694 UpperCAmelCase = 0.20_7951 UpperCAmelCase = 0.12_1194 UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = 0.035_2513 UpperCAmelCase = TapasForQuestionAnswering(config=_a ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams UpperCAmelCase = 4 UpperCAmelCase = False # hparam_utils.py hparams UpperCAmelCase = 36.4519 UpperCAmelCase = 0.90_3421 UpperCAmelCase = 222.088 UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = 0.76_3141 UpperCAmelCase = TapasForQuestionAnswering(config=_a ) elif task == "TABFACT": UpperCAmelCase = TapasForSequenceClassification(config=_a ) elif task == "MLM": UpperCAmelCase = TapasForMaskedLM(config=_a ) elif task == "INTERMEDIATE_PRETRAINING": UpperCAmelCase = TapasModel(config=_a ) else: raise ValueError(F"Task {task} not supported." ) print(F"Building PyTorch model from configuration: {config}" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(_a , _a , _a ) # Save pytorch-model (weights and configuration) print(F"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(_a ) # Save tokenizer files print(F"Save tokenizer files to {pytorch_dump_path}" ) UpperCAmelCase = TapasTokenizer(vocab_file=tf_checkpoint_path[:-1_0] + '''vocab.txt''' , model_max_length=5_1_2 ) tokenizer.save_pretrained(_a ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": A =argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
34
'''simple docstring''' import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowercase : Dict = 16 __lowercase : List[Any] = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return int(x / 2**20 ) class __UpperCamelCase : def __enter__( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero __a : Optional[int] = torch.cuda.memory_allocated() return self def __exit__( self , *__a ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() __a : Dict = torch.cuda.memory_allocated() __a : List[Any] = torch.cuda.max_memory_allocated() __a : Tuple = bamb(self.end - self.begin ) __a : Tuple = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def lowerCamelCase (_SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : int = 16 , _SCREAMING_SNAKE_CASE : str = "bert-base-cased" , _SCREAMING_SNAKE_CASE : int = 320 , _SCREAMING_SNAKE_CASE : int = 160 , ): __a : int = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : List[Any] = load_dataset( 'glue' , 'mrpc' , split={'train': F"""train[:{n_train}]""", 'validation': F"""validation[:{n_val}]"""} ) def tokenize_function(_SCREAMING_SNAKE_CASE : Tuple ): # max_length=None => use the model max length (it's actually the default) __a : Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a : List[str] = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=_SCREAMING_SNAKE_CASE ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : Tuple = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. __a : int = DataLoader( tokenized_datasets['train'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) __a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): # Initialize accelerator __a : str = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : Dict = config['lr'] __a : str = int(config['num_epochs'] ) __a : Optional[int] = int(config['seed'] ) __a : Any = int(config['batch_size'] ) __a : List[str] = args.model_name_or_path set_seed(_SCREAMING_SNAKE_CASE ) __a , __a : int = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : Optional[int] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE ) # Instantiate optimizer __a : Optional[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a : Optional[Any] = optimizer_cls(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) if accelerator.state.deepspeed_plugin is not None: __a : int = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: __a : Union[str, Any] = 1 __a : Tuple = (len(_SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a : str = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=0 , num_training_steps=_SCREAMING_SNAKE_CASE , ) else: __a : List[Any] = DummyScheduler(_SCREAMING_SNAKE_CASE , total_num_steps=_SCREAMING_SNAKE_CASE , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a : Optional[Any] = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # We need to keep track of how many total steps we have iterated over __a : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly __a : Dict = 0 # Now we train the model __a : str = {} for epoch in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): __a : List[Any] = model(**_SCREAMING_SNAKE_CASE ) __a : str = outputs.loss __a : str = loss / gradient_accumulation_steps accelerator.backward(_SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin ) ) ) accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used ) ) accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked ) ) accelerator.print( 'Total Peak Memory consumed during the train (max): {}'.format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) __a : List[Any] = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'peak_memory_utilization.json' ) , 'w' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : int = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=_SCREAMING_SNAKE_CASE , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_SCREAMING_SNAKE_CASE , ) parser.add_argument( '--output_dir' , type=_SCREAMING_SNAKE_CASE , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--peak_memory_upper_bound' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.' , ) parser.add_argument( '--n_train' , type=_SCREAMING_SNAKE_CASE , default=320 , help='Number of training examples to use.' , ) parser.add_argument( '--n_val' , type=_SCREAMING_SNAKE_CASE , default=160 , help='Number of validation examples to use.' , ) parser.add_argument( '--num_epochs' , type=_SCREAMING_SNAKE_CASE , default=1 , help='Number of train epochs.' , ) __a : List[str] = parser.parse_args() __a : List[Any] = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
27
0
'''simple docstring''' from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { "huggingface/autoformer-tourism-monthly": "https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json", } class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = "autoformer" lowercase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers", } def __init__( self : List[Any] , snake_case_ : Optional[int] = None , snake_case_ : Optional[int] = None , snake_case_ : str = "student_t" , snake_case_ : str = "nll" , snake_case_ : int = 1 , snake_case_ : List[int] = [1, 2, 3, 4, 5, 6, 7] , snake_case_ : bool = True , snake_case_ : int = 0 , snake_case_ : int = 0 , snake_case_ : int = 0 , snake_case_ : int = 0 , snake_case_ : Optional[List[int]] = None , snake_case_ : Optional[List[int]] = None , snake_case_ : int = 64 , snake_case_ : int = 2 , snake_case_ : int = 2 , snake_case_ : int = 2 , snake_case_ : int = 2 , snake_case_ : int = 32 , snake_case_ : int = 32 , snake_case_ : str = "gelu" , snake_case_ : float = 0.1 , snake_case_ : float = 0.1 , snake_case_ : float = 0.1 , snake_case_ : float = 0.1 , snake_case_ : float = 0.1 , snake_case_ : int = 100 , snake_case_ : float = 0.02 , snake_case_ : bool = True , snake_case_ : Optional[Any]=True , snake_case_ : int = 10 , snake_case_ : int = 25 , snake_case_ : int = 3 , **snake_case_ : Optional[int] , ): # time series specific configuration snake_case__ : Optional[Any] = prediction_length snake_case__ : List[str] = context_length if context_length is not None else prediction_length snake_case__ : List[str] = distribution_output snake_case__ : Dict = loss snake_case__ : List[str] = input_size snake_case__ : Any = num_time_features snake_case__ : Any = lags_sequence snake_case__ : List[Any] = scaling snake_case__ : List[Any] = num_dynamic_real_features snake_case__ : Union[str, Any] = num_static_real_features snake_case__ : List[str] = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(snake_case_ ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) snake_case__ : Union[str, Any] = cardinality else: snake_case__ : Union[str, Any] = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(snake_case_ ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) snake_case__ : Union[str, Any] = embedding_dimension else: snake_case__ : List[Any] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] snake_case__ : List[str] = num_parallel_samples # Transformer architecture configuration snake_case__ : str = input_size * len(self.lags_sequence ) + self._number_of_features snake_case__ : Optional[Any] = d_model snake_case__ : Optional[Any] = encoder_attention_heads snake_case__ : str = decoder_attention_heads snake_case__ : Any = encoder_ffn_dim snake_case__ : int = decoder_ffn_dim snake_case__ : Tuple = encoder_layers snake_case__ : Dict = decoder_layers snake_case__ : List[str] = dropout snake_case__ : Optional[Any] = attention_dropout snake_case__ : List[Any] = activation_dropout snake_case__ : Tuple = encoder_layerdrop snake_case__ : Tuple = decoder_layerdrop snake_case__ : int = activation_function snake_case__ : str = init_std snake_case__ : str = use_cache # Autoformer snake_case__ : Optional[Any] = label_length snake_case__ : Dict = moving_average snake_case__ : Tuple = autocorrelation_factor super().__init__(is_encoder_decoder=snake_case_ , **snake_case_ ) @property def lowerCamelCase ( self : List[str] ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
35
'''simple docstring''' import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer __lowercase : List[Any] = 'bart' __lowercase : Union[str, Any] = True @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : List[Any] = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) __a : Dict = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) __a : Optional[int] = qar_model.eval() else: __a , __a : str = (None, None) if MODEL_TYPE == "bart": __a : Union[str, Any] = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) __a : int = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) __a : Optional[Any] = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) __a : str = sas_model.eval() else: __a , __a : Tuple = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : Optional[Any] = faiss.StandardGpuResources() __a : Dict = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] __a : int = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 128) , ) __a : int = faiss.IndexFlatIP(128 ) __a : Any = faiss.index_cpu_to_gpu(_SCREAMING_SNAKE_CASE , 1 , _SCREAMING_SNAKE_CASE ) wikiaab_gpu_index_flat.add(_SCREAMING_SNAKE_CASE ) # TODO fix for larger GPU else: __a , __a : str = (None, None) __a : Optional[int] = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : Dict = datasets.load_dataset('eli5' , name='LFQA_reddit' ) __a : Dict = elia['train_eli5'] __a : Optional[int] = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 128) ) __a : str = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(_SCREAMING_SNAKE_CASE ) return (elia_train, eli5_train_q_index) __lowercase , __lowercase , __lowercase : Any = load_indexes() __lowercase , __lowercase , __lowercase , __lowercase : Dict = load_models() __lowercase , __lowercase : int = load_train_data() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str]=10 ): __a : Optional[int] = embed_questions_for_retrieval([question] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a , __a : Union[str, Any] = eli5_train_q_index.search(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [elia_train[int(_SCREAMING_SNAKE_CASE )] for i in I[0]] return nn_examples def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : str="wiki40b" , _SCREAMING_SNAKE_CASE : List[str]="dense" , _SCREAMING_SNAKE_CASE : Any=10 ): if source == "none": __a , __a : Any = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": __a , __a : str = query_qa_dense_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a , __a : Union[str, Any] = query_es_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index_name='english_wiki40b_snippets_100w' , n_results=_SCREAMING_SNAKE_CASE , ) __a : Dict = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] __a : Any = 'question: {} context: {}'.format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda _SCREAMING_SNAKE_CASE : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _SCREAMING_SNAKE_CASE : None), } ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Dict=64 , _SCREAMING_SNAKE_CASE : Dict=256 , _SCREAMING_SNAKE_CASE : Any=False , _SCREAMING_SNAKE_CASE : Tuple=2 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0.9_5 , _SCREAMING_SNAKE_CASE : str=0.8 ): with torch.no_grad(): __a : Union[str, Any] = qa_sas_generate( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , num_answers=1 , num_beams=_SCREAMING_SNAKE_CASE , min_len=_SCREAMING_SNAKE_CASE , max_len=_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE , temp=_SCREAMING_SNAKE_CASE , top_p=_SCREAMING_SNAKE_CASE , top_k=_SCREAMING_SNAKE_CASE , max_input_length=1_024 , device='cuda:0' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar __lowercase : Optional[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' __lowercase : str = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia __lowercase : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) __lowercase : Dict = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] __lowercase : Union[str, Any] = st.sidebar.checkbox('Demo options') if demo_options: __lowercase : Any = st.sidebar.selectbox( '', action_list, index=3, ) __lowercase : Tuple = action_list.index(action_st) __lowercase : Tuple = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) __lowercase : List[Any] = show_type == 'Show full text of passages' else: __lowercase : int = 3 __lowercase : str = True __lowercase : Tuple = st.sidebar.checkbox('Retrieval options') if retrieval_options: __lowercase : List[Any] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: __lowercase : str = 'wiki40b' __lowercase : List[Any] = 'dense' __lowercase : Dict = 'beam' __lowercase : Optional[int] = 2 __lowercase : List[str] = 64 __lowercase : Tuple = 2_56 __lowercase : List[str] = None __lowercase : Tuple = None __lowercase : List[Any] = st.sidebar.checkbox('Generation options') if generate_options: __lowercase : Optional[Any] = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) __lowercase : List[Any] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) __lowercase : Tuple = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=2_56, value=64, step=8, format=None, key=None ) __lowercase : int = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None ) if sampled == "beam": __lowercase : Any = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: __lowercase : Dict = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) __lowercase : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) __lowercase : List[str] = None # start main text __lowercase : int = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] __lowercase : Optional[int] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": __lowercase : Any = st.text_input('Enter your question here:', '') else: __lowercase : Any = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": __lowercase , __lowercase : Optional[int] = make_support(question, source=wiki_source, method='dense', n_results=10) __lowercase , __lowercase : List[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) __lowercase : Optional[int] = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] __lowercase : str = support_list[:10] __lowercase : Optional[int] = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: __lowercase , __lowercase : Optional[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: __lowercase , __lowercase : int = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): __lowercase : str = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) __lowercase : Any = res[1].strip() if sec_titles == "": __lowercase : List[str] = '[{}]({})'.format(res[0], wiki_url) else: __lowercase : Union[str, Any] = sec_titles.split(' & ') __lowercase : str = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: __lowercase : str = find_nearest_training(question) __lowercase : Optional[int] = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) __lowercase : Any = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) __lowercase : List[Any] = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
27
0
from collections.abc import Generator from math import sin def A ( _lowerCamelCase ): '''simple docstring''' if len(_lowerCamelCase ) != 32: raise ValueError("Input must be of length 32" ) _lowerCAmelCase : Optional[Any] = b"" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def A ( _lowerCamelCase ): '''simple docstring''' if i < 0: raise ValueError("Input must be non-negative" ) _lowerCAmelCase : Dict = format(_lowerCamelCase , "08x" )[-8:] _lowerCAmelCase : int = b"" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8" ) return little_endian_hex def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Tuple = b"" for char in message: bit_string += format(_lowerCamelCase , "08b" ).encode("utf-8" ) _lowerCAmelCase : Tuple = format(len(_lowerCamelCase ) , "064b" ).encode("utf-8" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(_lowerCamelCase ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def A ( _lowerCamelCase ): '''simple docstring''' if len(_lowerCamelCase ) % 512 != 0: raise ValueError("Input must have length that's a multiple of 512" ) for pos in range(0 , len(_lowerCamelCase ) , 512 ): _lowerCAmelCase : List[str] = bit_string[pos : pos + 512] _lowerCAmelCase : Optional[Any] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def A ( _lowerCamelCase ): '''simple docstring''' if i < 0: raise ValueError("Input must be non-negative" ) _lowerCAmelCase : str = format(_lowerCamelCase , "032b" ) _lowerCAmelCase : Optional[Any] = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(_lowerCamelCase , 2 ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' return (a + b) % 2**32 def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' if i < 0: raise ValueError("Input must be non-negative" ) if shift < 0: raise ValueError("Shift must be non-negative" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Dict = preprocess(_lowerCamelCase ) _lowerCAmelCase : Tuple = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states _lowerCAmelCase : int = 0X67_45_23_01 _lowerCAmelCase : Optional[Any] = 0XEF_CD_AB_89 _lowerCAmelCase : Union[str, Any] = 0X98_BA_DC_FE _lowerCAmelCase : Dict = 0X10_32_54_76 _lowerCAmelCase : int = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(_lowerCamelCase ): _lowerCAmelCase : Dict = aa _lowerCAmelCase : Union[str, Any] = ba _lowerCAmelCase : Dict = ca _lowerCAmelCase : Tuple = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f _lowerCAmelCase : List[Any] = d ^ (b & (c ^ d)) _lowerCAmelCase : int = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f _lowerCAmelCase : List[str] = c ^ (d & (b ^ c)) _lowerCAmelCase : Dict = (5 * i + 1) % 16 elif i <= 47: _lowerCAmelCase : Union[str, Any] = b ^ c ^ d _lowerCAmelCase : Optional[int] = (3 * i + 5) % 16 else: _lowerCAmelCase : List[str] = c ^ (b | not_aa(_lowerCamelCase )) _lowerCAmelCase : int = (7 * i) % 16 _lowerCAmelCase : int = (f + a + added_consts[i] + block_words[g]) % 2**32 _lowerCAmelCase : Optional[int] = d _lowerCAmelCase : Tuple = c _lowerCAmelCase : int = b _lowerCAmelCase : Tuple = sum_aa(_lowerCamelCase , left_rotate_aa(_lowerCamelCase , shift_amounts[i] ) ) # Add hashed chunk to running total _lowerCAmelCase : List[str] = sum_aa(_lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : Any = sum_aa(_lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : Any = sum_aa(_lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : str = sum_aa(_lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = reformat_hex(_lowerCamelCase ) + reformat_hex(_lowerCamelCase ) + reformat_hex(_lowerCamelCase ) + reformat_hex(_lowerCamelCase ) return digest if __name__ == "__main__": import doctest doctest.testmod()
36
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __lowercase : Tuple = logging.get_logger(__name__) __lowercase : List[Any] = torch.device('cpu') def lowerCamelCase (): __a : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __a : Tuple = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0, 8.8_6_8_5e-0_1, 2.4_3_6_0e-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6e-0_1, 2.3_4_7_8e-0_1, -1.6_9_6_3e0_0, -1.7_3_8_1e0_0, -8.6_3_3_7e-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8e-0_1, -4.7_4_2_9e-0_1, -1.0_8_9_7e0_0, -1.0_2_4_8e0_0, 3.5_5_2_3e-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0e-0_1, 2.4_2_1_1e-0_1, -6.0_1_8_5e-0_1, -8.2_7_8_9e-0_1, -6.0_4_4_6e-0_2] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : int = dct.pop(_SCREAMING_SNAKE_CASE ) __a : Tuple = val def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : Dict = [] for k in state_dict.keys(): __a : List[Any] = k if ".pwconv" in k: __a : List[Any] = k_new.replace('.pwconv' , '.point_wise_conv' ) if ".dwconv" in k: __a : Dict = k_new.replace('.dwconv' , '.depth_wise_conv' ) if ".Proj." in k: __a : Optional[int] = k_new.replace('.Proj.' , '.proj.' ) if "patch_embed" in k_new: __a : List[Any] = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' ) if "network" in k_new: __a : Union[str, Any] = k_new.split('.' ) if ls[2].isdigit(): __a : Union[str, Any] = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] ) else: __a : Union[str, Any] = k_new.replace('network' , 'swiftformer.encoder.network' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Union[str, Any] = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size __a : List[str] = 1_000 __a : Tuple = 'huggingface/label-files' __a : str = 'imagenet-1k-id2label.json' __a : Dict = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) __a : Optional[int] = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a : Any = idalabel __a : str = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": __a : Dict = [3, 3, 6, 4] __a : int = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": __a : Dict = [3, 3, 9, 6] __a : List[str] = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": __a : Dict = [4, 3, 10, 5] __a : Optional[int] = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": __a : Tuple = [4, 4, 12, 6] __a : Dict = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('https' ): __a : List[Any] = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE ) else: __a : Union[str, Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) __a : Optional[Any] = checkpoint __a : Dict = create_rename_keys(_SCREAMING_SNAKE_CASE ) for rename_key_src, rename_key_dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model __a : Tuple = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval() hf_model.load_state_dict(_SCREAMING_SNAKE_CASE ) # prepare test inputs __a : Tuple = prepare_img() __a : str = ViTImageProcessor.from_pretrained('preprocessor_config' ) __a : Tuple = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # compare outputs from both models __a : List[Any] = get_expected_output(_SCREAMING_SNAKE_CASE ) __a : Dict = hf_model(inputs['pixel_values'] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swiftformer_name', default='swiftformer_xs', choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'], type=str, help='Name of the SwiftFormer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='./converted_outputs/', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.') __lowercase : Tuple = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
27
0
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ : Tuple = position lowerCAmelCase__ : int = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] lowerCAmelCase__ : int = [] for position in positions: lowerCAmelCase__ , lowerCAmelCase__ : Dict = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(UpperCamelCase ) return permissible_positions def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" return not any(elem == 0 for row in board for elem in row ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" if is_complete(UpperCamelCase ): return True for position in get_valid_pos(UpperCamelCase , len(UpperCamelCase ) ): lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = position if board[y][x] == 0: lowerCAmelCase__ : List[str] = curr + 1 if open_knight_tour_helper(UpperCamelCase , UpperCamelCase , curr + 1 ): return True lowerCAmelCase__ : Optional[int] = 0 return False def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Tuple = [[0 for i in range(UpperCamelCase )] for j in range(UpperCamelCase )] for i in range(UpperCamelCase ): for j in range(UpperCamelCase ): lowerCAmelCase__ : int = 1 if open_knight_tour_helper(UpperCamelCase , (i, j) , 1 ): return board lowerCAmelCase__ : Any = 0 lowerCAmelCase__ : Optional[int] = f"""Open Kight Tour cannot be performed on a board of size {n}""" raise ValueError(UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
37
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __lowercase : Dict = logging.get_logger(__name__) __lowercase : Optional[Any] = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "umt5" A_ = ["past_key_values"] def __init__( self , __a=25_0112 , __a=512 , __a=64 , __a=1024 , __a=8 , __a=None , __a=6 , __a=32 , __a=128 , __a=0.1 , __a=1E-6 , __a=1.0 , __a="gated-gelu" , __a=True , __a=True , __a="T5Tokenizer" , __a=True , __a=0 , __a=1 , __a=0 , **__a , ): '''simple docstring''' super().__init__( is_encoder_decoder=__a , tokenizer_class=__a , tie_word_embeddings=__a , pad_token_id=__a , eos_token_id=__a , decoder_start_token_id=__a , **__a , ) __a : Any = vocab_size __a : Any = d_model __a : str = d_kv __a : Dict = d_ff __a : Union[str, Any] = num_layers __a : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __a : Optional[int] = num_heads __a : Tuple = relative_attention_num_buckets __a : Optional[Any] = relative_attention_max_distance __a : Optional[int] = dropout_rate __a : List[Any] = layer_norm_epsilon __a : int = initializer_factor __a : Union[str, Any] = feed_forward_proj __a : Any = use_cache __a : List[Any] = self.feed_forward_proj.split('-' ) __a : Dict = act_info[-1] __a : Dict = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) if feed_forward_proj == "gated-gelu": __a : Optional[int] = 'gelu_new' @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.d_model @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_heads @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_layers class __UpperCamelCase ( lowerCAmelCase_ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __a : Dict = 'past_encoder_sequence + sequence' __a : Tuple = {0: 'batch'} __a : Tuple = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __a : List[Any] = {0: 'batch', 1: 'decoder_sequence'} __a : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __UpperCAmelCase ( self ): '''simple docstring''' return 13 @property def __UpperCAmelCase ( self ): '''simple docstring''' return 5E-4
27
0
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : Any ) -> Any: """simple docstring""" UpperCamelCase :List[str] = checkpoint UpperCamelCase :Optional[int] = {} UpperCamelCase :Any = vae_state_dict["""encoder.conv_in.weight"""] UpperCamelCase :Union[str, Any] = vae_state_dict["""encoder.conv_in.bias"""] UpperCamelCase :Optional[int] = vae_state_dict["""encoder.conv_out.weight"""] UpperCamelCase :str = vae_state_dict["""encoder.conv_out.bias"""] UpperCamelCase :str = vae_state_dict["""encoder.norm_out.weight"""] UpperCamelCase :Optional[int] = vae_state_dict["""encoder.norm_out.bias"""] UpperCamelCase :Optional[int] = vae_state_dict["""decoder.conv_in.weight"""] UpperCamelCase :int = vae_state_dict["""decoder.conv_in.bias"""] UpperCamelCase :str = vae_state_dict["""decoder.conv_out.weight"""] UpperCamelCase :Union[str, Any] = vae_state_dict["""decoder.conv_out.bias"""] UpperCamelCase :Optional[Any] = vae_state_dict["""decoder.norm_out.weight"""] UpperCamelCase :List[Any] = vae_state_dict["""decoder.norm_out.bias"""] UpperCamelCase :List[str] = vae_state_dict["""quant_conv.weight"""] UpperCamelCase :Any = vae_state_dict["""quant_conv.bias"""] UpperCamelCase :int = vae_state_dict["""post_quant_conv.weight"""] UpperCamelCase :List[Any] = vae_state_dict["""post_quant_conv.bias"""] # Retrieves the keys for the encoder down blocks only UpperCamelCase :List[str] = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """encoder.down""" in layer} ) UpperCamelCase :Optional[int] = { layer_id: [key for key in vae_state_dict if f"""down.{layer_id}""" in key] for layer_id in range(__magic_name__ ) } # Retrieves the keys for the decoder up blocks only UpperCamelCase :Optional[int] = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """decoder.up""" in layer} ) UpperCamelCase :Optional[Any] = { layer_id: [key for key in vae_state_dict if f"""up.{layer_id}""" in key] for layer_id in range(__magic_name__ ) } for i in range(__magic_name__ ): UpperCamelCase :Tuple = [key for key in down_blocks[i] if f"""down.{i}""" in key and f"""down.{i}.downsample""" not in key] if f"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict: UpperCamelCase :Any = vae_state_dict.pop( f"""encoder.down.{i}.downsample.conv.weight""" ) UpperCamelCase :Union[str, Any] = vae_state_dict.pop( f"""encoder.down.{i}.downsample.conv.bias""" ) UpperCamelCase :Any = renew_vae_resnet_paths(__magic_name__ ) UpperCamelCase :str = {"""old""": f"""down.{i}.block""", """new""": f"""down_blocks.{i}.resnets"""} assign_to_checkpoint(__magic_name__ , __magic_name__ , __magic_name__ , additional_replacements=[meta_path] , config=__magic_name__ ) UpperCamelCase :Optional[Any] = [key for key in vae_state_dict if """encoder.mid.block""" in key] UpperCamelCase :Dict = 2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCamelCase :int = [key for key in mid_resnets if f"""encoder.mid.block_{i}""" in key] UpperCamelCase :List[Any] = renew_vae_resnet_paths(__magic_name__ ) UpperCamelCase :str = {"""old""": f"""mid.block_{i}""", """new""": f"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(__magic_name__ , __magic_name__ , __magic_name__ , additional_replacements=[meta_path] , config=__magic_name__ ) UpperCamelCase :List[Any] = [key for key in vae_state_dict if """encoder.mid.attn""" in key] UpperCamelCase :List[str] = renew_vae_attention_paths(__magic_name__ ) UpperCamelCase :List[str] = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(__magic_name__ , __magic_name__ , __magic_name__ , additional_replacements=[meta_path] , config=__magic_name__ ) conv_attn_to_linear(__magic_name__ ) for i in range(__magic_name__ ): UpperCamelCase :Optional[int] = num_up_blocks - 1 - i UpperCamelCase :List[Any] = [ key for key in up_blocks[block_id] if f"""up.{block_id}""" in key and f"""up.{block_id}.upsample""" not in key ] if f"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict: UpperCamelCase :str = vae_state_dict[ f"""decoder.up.{block_id}.upsample.conv.weight""" ] UpperCamelCase :int = vae_state_dict[ f"""decoder.up.{block_id}.upsample.conv.bias""" ] UpperCamelCase :int = renew_vae_resnet_paths(__magic_name__ ) UpperCamelCase :List[Any] = {"""old""": f"""up.{block_id}.block""", """new""": f"""up_blocks.{i}.resnets"""} assign_to_checkpoint(__magic_name__ , __magic_name__ , __magic_name__ , additional_replacements=[meta_path] , config=__magic_name__ ) UpperCamelCase :Optional[int] = [key for key in vae_state_dict if """decoder.mid.block""" in key] UpperCamelCase :str = 2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCamelCase :Optional[Any] = [key for key in mid_resnets if f"""decoder.mid.block_{i}""" in key] UpperCamelCase :List[str] = renew_vae_resnet_paths(__magic_name__ ) UpperCamelCase :int = {"""old""": f"""mid.block_{i}""", """new""": f"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(__magic_name__ , __magic_name__ , __magic_name__ , additional_replacements=[meta_path] , config=__magic_name__ ) UpperCamelCase :List[Any] = [key for key in vae_state_dict if """decoder.mid.attn""" in key] UpperCamelCase :Optional[Any] = renew_vae_attention_paths(__magic_name__ ) UpperCamelCase :Union[str, Any] = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(__magic_name__ , __magic_name__ , __magic_name__ , additional_replacements=[meta_path] , config=__magic_name__ ) conv_attn_to_linear(__magic_name__ ) return new_checkpoint def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : str , ) -> Optional[int]: """simple docstring""" UpperCamelCase :Tuple = requests.get( """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml""" ) UpperCamelCase :int = io.BytesIO(r.content ) UpperCamelCase :str = OmegaConf.load(__magic_name__ ) UpperCamelCase :str = 512 UpperCamelCase :List[Any] = """cuda""" if torch.cuda.is_available() else """cpu""" if checkpoint_path.endswith("""safetensors""" ): from safetensors import safe_open UpperCamelCase :List[str] = {} with safe_open(__magic_name__ , framework="""pt""" , device="""cpu""" ) as f: for key in f.keys(): UpperCamelCase :List[str] = f.get_tensor(__magic_name__ ) else: UpperCamelCase :Optional[int] = torch.load(__magic_name__ , map_location=__magic_name__ )["""state_dict"""] # Convert the VAE model. UpperCamelCase :Union[str, Any] = create_vae_diffusers_config(__magic_name__ , image_size=__magic_name__ ) UpperCamelCase :Union[str, Any] = custom_convert_ldm_vae_checkpoint(__magic_name__ , __magic_name__ ) UpperCamelCase :str = AutoencoderKL(**__magic_name__ ) vae.load_state_dict(__magic_name__ ) vae.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : Any = argparse.ArgumentParser() parser.add_argument('''--vae_pt_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') UpperCAmelCase_ : Any = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
38
'''simple docstring''' import requests from bsa import BeautifulSoup def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "https://www.worldometers.info/coronavirus" ): __a : List[Any] = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE ).text , 'html.parser' ) __a : Union[str, Any] = soup.findAll('h1' ) __a : int = soup.findAll('div' , {'class': 'maincounter-number'} ) keys += soup.findAll('span' , {'class': 'panel-title'} ) values += soup.findAll('div' , {'class': 'number-table-main'} ) return {key.text.strip(): value.text.strip() for key, value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
27
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _a = { '''configuration_longt5''': ['''LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LongT5Config''', '''LongT5OnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ '''LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LongT5EncoderModel''', '''LongT5ForConditionalGeneration''', '''LongT5Model''', '''LongT5PreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ '''FlaxLongT5ForConditionalGeneration''', '''FlaxLongT5Model''', '''FlaxLongT5PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys _a = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
39
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__a , 'embed_dim' ) ) self.parent.assertTrue(hasattr(__a , 'num_heads' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=64 , __a=3 , __a=[16, 48, 96] , __a=[1, 3, 6] , __a=[1, 2, 10] , __a=[7, 3, 3] , __a=[4, 2, 2] , __a=[2, 1, 1] , __a=[2, 2, 2] , __a=[False, False, True] , __a=[0.0, 0.0, 0.0] , __a=0.02 , __a=1E-1_2 , __a=True , __a=True , __a=2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : Optional[int] = image_size __a : List[str] = patch_sizes __a : str = patch_stride __a : Any = patch_padding __a : Dict = is_training __a : Union[str, Any] = use_labels __a : Dict = num_labels __a : List[Any] = num_channels __a : Any = embed_dim __a : int = num_heads __a : Optional[int] = stride_kv __a : Dict = depth __a : List[str] = cls_token __a : List[Any] = attention_drop_rate __a : Tuple = initializer_range __a : int = layer_norm_eps def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Dict = None if self.use_labels: # create a random int32 tensor of given shape __a : str = ids_tensor([self.batch_size] , self.num_labels ) __a : str = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = TFCvtModel(config=__a ) __a : Dict = model(__a , training=__a ) __a : Any = (self.image_size, self.image_size) __a , __a : Dict = image_size[0], image_size[1] for i in range(len(self.depth ) ): __a : Tuple = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) __a : str = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : List[Any] = self.num_labels __a : Optional[int] = TFCvtForImageClassification(__a ) __a : Dict = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () A_ = ( {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification} if is_tf_available() else {} ) A_ = False A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtModelTester(self ) __a : List[Any] = TFCvtConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason='Cvt does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = tf.keras.mixed_precision.Policy('mixed_float16' ) tf.keras.mixed_precision.set_global_policy(__a ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('float32' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : List[str] = model_class(__a ) __a : Union[str, Any] = model(**self._prepare_for_class(__a , __a ) ) __a : Any = outputs.hidden_states __a : Union[str, Any] = len(self.model_tester.depth ) self.assertEqual(len(__a ) , __a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[str] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[Any] = TFCvtModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __a : Tuple = self.default_image_processor __a : Any = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ) # forward pass __a : Any = model(**__a ) # verify the logits __a : Any = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __a : Optional[Any] = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __a , atol=1E-4 ) )
27
0
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class _A ( _a ): """simple docstring""" UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] UpperCAmelCase : Optional[List[bool]] UpperCAmelCase : Optional[List[bool]] 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 .pipeline_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
40
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __lowercase : Union[str, Any] = logging.get_logger(__name__) __lowercase : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } __lowercase : Optional[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): for attribute in key.split('.' ): __a : Any = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: __a : Any = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __a : Tuple = value elif weight_type == "weight_g": __a : str = value elif weight_type == "weight_v": __a : Optional[Any] = value elif weight_type == "bias": __a : Union[str, Any] = value else: __a : List[Any] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : int = [] __a : List[str] = fairseq_model.state_dict() __a : Tuple = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight __a : int = None for name, value in fairseq_dict.items(): __a : List[str] = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == 'group' , ) __a : List[str] = True elif name.split('.' )[0] == "proj": __a : Tuple = fairseq_model.proj __a : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __a : List[Any] = True if "*" in mapped_key: __a : str = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2] __a : int = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: __a : List[Any] = 'weight_g' elif "weight_v" in name: __a : List[Any] = 'weight_v' elif "bias" in name: __a : Optional[Any] = 'bias' elif "weight" in name: __a : Tuple = 'weight' else: __a : Optional[Any] = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : List[str] = full_name.split('conv_layers.' )[-1] __a : Any = name.split('.' ) __a : List[str] = int(items[0] ) __a : List[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __a : List[str] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __a : str = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) __a : Tuple = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __a : List[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a , __a : List[str] = emb.weight.shape __a : str = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) __a : Optional[int] = emb.weight.data return lin_layer def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any ): with open(_SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' ) as f: __a : Union[str, Any] = f.readlines() __a : Tuple = [line.split(' ' )[0] for line in lines] __a : int = len(_SCREAMING_SNAKE_CASE ) __a : List[Any] = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(_SCREAMING_SNAKE_CASE , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int] , ): __a : Optional[int] = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : Any = SpeechaTextaConfig.from_pretrained( _SCREAMING_SNAKE_CASE , vocab_size=_SCREAMING_SNAKE_CASE , decoder_layers=_SCREAMING_SNAKE_CASE , do_stable_layer_norm=_SCREAMING_SNAKE_CASE ) __a : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) __a , __a , __a : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) __a : Optional[int] = model[0].eval() # set weights for wav2vec2 encoder __a : Tuple = WavaVecaModel(_SCREAMING_SNAKE_CASE ) __a : int = recursively_load_weights_wavaveca(model.encoder , _SCREAMING_SNAKE_CASE ) __a : Dict = SpeechaTextaForCausalLM(_SCREAMING_SNAKE_CASE ) __a , __a : Optional[int] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_SCREAMING_SNAKE_CASE ) # set output linear layer unexpected_keys.remove('embed_out' ) __a : Optional[Any] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) __a : Tuple = SpeechEncoderDecoderModel(encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) __a : int = False # add projection layer __a : str = nn.Parameter(projection_layer.weight ) __a : Any = nn.Parameter(projection_layer.bias ) __a : str = create_vocab_dict(_SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) , 'w' ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = SpeechaTextaTokenizer(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) ) tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = hf_wavavec.config.to_dict() __a : Tuple = tokenizer.pad_token_id __a : Optional[int] = tokenizer.bos_token_id __a : Union[str, Any] = tokenizer.eos_token_id __a : Tuple = 'speech_to_text_2' __a : Tuple = 'wav2vec2' __a : List[str] = SpeechEncoderDecoderConfig.from_dict(_SCREAMING_SNAKE_CASE ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-large-lv60', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/s2t-small-mustc-en-fr-st', type=str, help='Path to hf decoder s2t checkpoint config', ) parser.add_argument('--vocab_size', default=1_02_24, type=int, help='Vocab size of decoder') parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers') __lowercase : Tuple = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
27
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _A : Dict =logging.get_logger(__name__) _A : Any ={ '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class _lowercase ( _lowercase ): a = """table-transformer""" a = ["""past_key_values"""] a = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self: Dict , UpperCamelCase__: Any=True , UpperCamelCase__: str=None , UpperCamelCase__: List[Any]=3 , UpperCamelCase__: Any=100 , UpperCamelCase__: str=6 , UpperCamelCase__: Tuple=2_048 , UpperCamelCase__: Any=8 , UpperCamelCase__: List[str]=6 , UpperCamelCase__: Union[str, Any]=2_048 , UpperCamelCase__: Dict=8 , UpperCamelCase__: List[Any]=0.0 , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: Dict=True , UpperCamelCase__: List[str]="relu" , UpperCamelCase__: Optional[Any]=256 , UpperCamelCase__: Dict=0.1 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: str=0.0 , UpperCamelCase__: List[str]=0.02 , UpperCamelCase__: Union[str, Any]=1.0 , UpperCamelCase__: Dict=False , UpperCamelCase__: Dict="sine" , UpperCamelCase__: str="resnet50" , UpperCamelCase__: List[str]=True , UpperCamelCase__: Tuple=False , UpperCamelCase__: List[str]=1 , UpperCamelCase__: Tuple=5 , UpperCamelCase__: Any=2 , UpperCamelCase__: Optional[int]=1 , UpperCamelCase__: Tuple=1 , UpperCamelCase__: List[Any]=5 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: int=0.1 , **UpperCamelCase__: Optional[int] , ): if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase__ : str = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : Optional[int] = backbone_config.get("""model_type""" ) lowerCamelCase__ : Tuple = CONFIG_MAPPING[backbone_model_type] lowerCamelCase__ : str = config_class.from_dict(UpperCamelCase__ ) # set timm attributes to None lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Optional[int] = None, None, None lowerCamelCase__ : Union[str, Any] = use_timm_backbone lowerCamelCase__ : Optional[Any] = backbone_config lowerCamelCase__ : Any = num_channels lowerCamelCase__ : Tuple = num_queries lowerCamelCase__ : Dict = d_model lowerCamelCase__ : List[Any] = encoder_ffn_dim lowerCamelCase__ : int = encoder_layers lowerCamelCase__ : Union[str, Any] = encoder_attention_heads lowerCamelCase__ : Dict = decoder_ffn_dim lowerCamelCase__ : List[Any] = decoder_layers lowerCamelCase__ : Any = decoder_attention_heads lowerCamelCase__ : Any = dropout lowerCamelCase__ : List[Any] = attention_dropout lowerCamelCase__ : List[str] = activation_dropout lowerCamelCase__ : List[Any] = activation_function lowerCamelCase__ : Tuple = init_std lowerCamelCase__ : List[str] = init_xavier_std lowerCamelCase__ : Optional[int] = encoder_layerdrop lowerCamelCase__ : Any = decoder_layerdrop lowerCamelCase__ : int = encoder_layers lowerCamelCase__ : Tuple = auxiliary_loss lowerCamelCase__ : Tuple = position_embedding_type lowerCamelCase__ : List[Any] = backbone lowerCamelCase__ : Optional[Any] = use_pretrained_backbone lowerCamelCase__ : Any = dilation # Hungarian matcher lowerCamelCase__ : Dict = class_cost lowerCamelCase__ : Union[str, Any] = bbox_cost lowerCamelCase__ : Any = giou_cost # Loss coefficients lowerCamelCase__ : Any = mask_loss_coefficient lowerCamelCase__ : Dict = dice_loss_coefficient lowerCamelCase__ : Union[str, Any] = bbox_loss_coefficient lowerCamelCase__ : List[Any] = giou_loss_coefficient lowerCamelCase__ : List[str] = eos_coefficient super().__init__(is_encoder_decoder=UpperCamelCase__ , **UpperCamelCase__ ) @property def lowerCamelCase_ ( self: List[Any] ): return self.encoder_attention_heads @property def lowerCamelCase_ ( self: Optional[Any] ): return self.d_model class _lowercase ( _lowercase ): a = version.parse("""1.11""" ) @property def lowerCamelCase_ ( self: Any ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def lowerCamelCase_ ( self: List[Any] ): return 1e-5 @property def lowerCamelCase_ ( self: Tuple ): return 12
41
'''simple docstring''' # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int ): with open(_SCREAMING_SNAKE_CASE , 'r' ) as fh: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_EX ) try: print(*_SCREAMING_SNAKE_CASE ) finally: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) __lowercase : Dict = int(os.environ['LOCAL_RANK']) torch.cuda.set_device(local_rank) __lowercase : Tuple = torch.device('cuda', local_rank) __lowercase : Optional[int] = socket.gethostname() __lowercase : List[str] = f'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group('nccl') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __lowercase : str = dist.get_rank() __lowercase : Union[str, Any] = dist.get_world_size() printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(f'''{gpu} is broken''') raise
27
0
'''simple docstring''' from copy import deepcopy class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): """simple docstring""" if arr is None and size is not None: _snake_case = size _snake_case = [0] * size elif arr is not None: self.init(lowerCAmelCase_ ) else: raise ValueError('Either arr or size must be specified' ) def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = len(lowerCAmelCase_ ) _snake_case = deepcopy(lowerCAmelCase_ ) for i in range(1 , self.size ): _snake_case = self.next_(lowerCAmelCase_ ) if j < self.size: self.tree[j] += self.tree[i] def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): _snake_case = self.next_(lowerCAmelCase_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowerCamelCase ( lowerCAmelCase_ ): """simple docstring""" return index + (index & (-index)) @staticmethod def lowerCamelCase ( lowerCAmelCase_ ): """simple docstring""" return index - (index & (-index)) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value _snake_case = self.next_(lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" self.add(lowerCAmelCase_ , value - self.get(lowerCAmelCase_ ) ) def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" if right == 0: return 0 _snake_case = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] _snake_case = self.prev(lowerCAmelCase_ ) return result def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" return self.prefix(lowerCAmelCase_ ) - self.prefix(lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" return self.query(lowerCAmelCase_ , index + 1 ) def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" value -= self.tree[0] if value < 0: return -1 _snake_case = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 _snake_case = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase : str = { '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: __lowercase : str = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] __lowercase : Tuple = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] __lowercase : Dict = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): __lowercase : Optional[Any] = [ '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 __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __lowercase = logging.getLogger(__name__) @dataclass class lowerCamelCase_ : '''simple docstring''' a__ : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a__ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) a__ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a__ : bool = field(default=UpperCAmelCase_ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. a__ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class lowerCamelCase_ : '''simple docstring''' a__ : str = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) a__ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) a__ : int = field( default=1_2_8 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : bool = field( default=UpperCAmelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def lowerCamelCase ( ): '''simple docstring''' __UpperCamelCase :Optional[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __UpperCamelCase , __UpperCamelCase , __UpperCamelCase :Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase :List[Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ''' --overwrite_output_dir to overcome.''' ) __UpperCamelCase :List[str] = import_module('''tasks''' ) try: __UpperCamelCase :Any = getattr(SCREAMING_SNAKE_CASE , model_args.task_type ) __UpperCamelCase :TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ f"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , SCREAMING_SNAKE_CASE ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __UpperCamelCase :Optional[Any] = token_classification_task.get_labels(data_args.labels ) __UpperCamelCase :Dict[int, str] = dict(enumerate(SCREAMING_SNAKE_CASE ) ) __UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __UpperCamelCase :int = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=SCREAMING_SNAKE_CASE , idalabel=SCREAMING_SNAKE_CASE , labelaid={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} , cache_dir=model_args.cache_dir , ) __UpperCamelCase :str = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __UpperCamelCase :int = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) # Get datasets __UpperCamelCase :List[str] = ( TokenClassificationDataset( token_classification_task=SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __UpperCamelCase :Optional[Any] = ( TokenClassificationDataset( token_classification_task=SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple[List[int], List[int]]: __UpperCamelCase :Dict = np.argmax(SCREAMING_SNAKE_CASE , axis=2 ) __UpperCamelCase , __UpperCamelCase :Any = preds.shape __UpperCamelCase :List[str] = [[] for _ in range(SCREAMING_SNAKE_CASE )] __UpperCamelCase :Optional[Any] = [[] for _ in range(SCREAMING_SNAKE_CASE )] for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(SCREAMING_SNAKE_CASE ) -> Dict: __UpperCamelCase , __UpperCamelCase :str = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), "precision": precision_score(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), "recall": recall_score(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), "f1": fa_score(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), } # Data collator __UpperCamelCase :str = DataCollatorWithPadding(SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __UpperCamelCase :List[Any] = Trainer( model=SCREAMING_SNAKE_CASE , args=SCREAMING_SNAKE_CASE , train_dataset=SCREAMING_SNAKE_CASE , eval_dataset=SCREAMING_SNAKE_CASE , compute_metrics=SCREAMING_SNAKE_CASE , data_collator=SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __UpperCamelCase :Any = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __UpperCamelCase :Dict = trainer.evaluate() __UpperCamelCase :str = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) writer.write('''%s = %s\n''' % (key, value) ) results.update(SCREAMING_SNAKE_CASE ) # Predict if training_args.do_predict: __UpperCamelCase :str = TokenClassificationDataset( token_classification_task=SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase :Optional[Any] = trainer.predict(SCREAMING_SNAKE_CASE ) __UpperCamelCase , __UpperCamelCase :Dict = align_predictions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __UpperCamelCase :Tuple = os.path.join(training_args.output_dir , '''test_results.txt''' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE , '''w''' ) as writer: for key, value in metrics.items(): logger.info(''' %s = %s''' , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) writer.write('''%s = %s\n''' % (key, value) ) # Save predictions __UpperCamelCase :Any = os.path.join(training_args.output_dir , '''test_predictions.txt''' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE , '''w''' ) as writer: with open(os.path.join(data_args.data_dir , '''test.txt''' ) , '''r''' ) as f: token_classification_task.write_predictions_to_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return results def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' main() if __name__ == "__main__": main()
43
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration __lowercase : Tuple = pytest.mark.integration __lowercase : Optional[int] = {'comet'} __lowercase : List[str] = importlib.util.find_spec('fairseq') is not None __lowercase : str = {'code_eval'} __lowercase : List[Any] = os.name == 'nt' __lowercase : Optional[Any] = {'bertscore', 'frugalscore', 'perplexity'} __lowercase : Optional[Any] = importlib.util.find_spec('transformers') is not None def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : int , _SCREAMING_SNAKE_CASE : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (): __a : List[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) @local class __UpperCamelCase ( parameterized.TestCase ): A_ = {} A_ = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = '[...]' __a : Tuple = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) __a : Optional[Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=__a ) # check parameters __a : Dict = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__a , metric_module.__name__ ): with self.use_local_metrics(): try: __a : str = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = '[...]' __a : Optional[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) # run doctest with self.use_local_metrics(): __a : List[Any] = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__a ): yield else: yield @contextmanager def __UpperCAmelCase ( self ): '''simple docstring''' def load_local_metric(__a , *__a , **__a ): return load_metric(os.path.join('metrics' , __a ) , *__a , **__a ) with patch('datasets.load_metric' ) as mock_load_metric: __a : Dict = load_local_metric yield @classmethod def __UpperCAmelCase ( cls , __a ): '''simple docstring''' def wrapper(__a ): __a : Optional[Any] = contextmanager(__a ) __a : str = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self , __a ): '''simple docstring''' assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: __a : Dict = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): import torch def bert_cos_score_idf(_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , *_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Optional[int] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: __a : str = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): def load_from_checkpoint(_SCREAMING_SNAKE_CASE : Optional[int] ): class __UpperCamelCase : def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' assert len(__a ) == 2 __a : Dict = [0.19, 0.92] return scores, sum(__a ) / len(__a ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: __a : str = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: __a : int = load_from_checkpoint yield def lowerCamelCase (): __a : Optional[Any] = load_metric(os.path.join('metrics' , 'seqeval' ) ) __a : List[str] = 'ERROR' __a : List[str] = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): metric.compute(predictions=[] , references=[] , scheme=_SCREAMING_SNAKE_CASE )
27
0
"""simple docstring""" _a : Union[str, Any] = '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
44
'''simple docstring''' import re import string import numpy as np import datasets __lowercase : Tuple = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' __lowercase : List[str] = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' __lowercase : Any = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def __UpperCAmelCase ( 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' ), } ) , reference_urls=[] , ) def __UpperCAmelCase ( self , __a , __a , __a=None , __a=False , __a=False , __a=False , ): '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: __a : Tuple = np.array([re.sub(__a , '' , __a ) for x in predictions] ) __a : List[Any] = np.array([re.sub(__a , '' , __a ) for x in references] ) else: __a : int = np.asarray(__a ) __a : str = np.asarray(__a ) if ignore_case: __a : Dict = np.char.lower(__a ) __a : List[str] = np.char.lower(__a ) if ignore_punctuation: __a : Dict = string.punctuation.maketrans('' , '' , string.punctuation ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Dict = np.char.translate(__a , table=__a ) if ignore_numbers: __a : Optional[int] = string.digits.maketrans('' , '' , string.digits ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Optional[int] = np.char.translate(__a , table=__a ) __a : Any = predictions == references return {"exact_match": np.mean(__a ) * 100}
27
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = 'xmod' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=1 , _a=0 , _a=2 , _a="absolute" , _a=True , _a=None , _a=False , _a=2 , _a=False , _a=True , _a=True , _a=("en_XX",) , _a=None , **_a , ): super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = use_cache __a = classifier_dropout __a = pre_norm __a = adapter_reduction_factor __a = adapter_layer_norm __a = adapter_reuse_layer_norm __a = ln_before_adapter __a = list(_a ) __a = default_language class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCAmelCase ( self ): if self.task == "multiple-choice": __a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
45
'''simple docstring''' import os import sys __lowercase : List[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowercase : int = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[str] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoConfig.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoTokenizer.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : str , **_SCREAMING_SNAKE_CASE : Any ): return AutoTokenizer.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModel.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Union[str, Any] ): return AutoModel.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[Any] , **_SCREAMING_SNAKE_CASE : Optional[int] ): return AutoModelForCausalLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Union[str, Any] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoModelForMaskedLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Optional[Any] , **_SCREAMING_SNAKE_CASE : Any ): return AutoModelForSequenceClassification.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Any , **_SCREAMING_SNAKE_CASE : List[str] ): return AutoModelForQuestionAnswering.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
27
0
"""simple docstring""" from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowercase ( _UpperCAmelCase ): def __init__( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = False , lowercase = False , lowercase = None , **lowercase , ) -> int: super().__init__( lowercase , split=lowercase , features=lowercase , cache_dir=lowercase , keep_in_memory=lowercase , streaming=lowercase , num_proc=lowercase , **lowercase , ) lowerCAmelCase = path_or_paths if isinstance(lowercase , lowercase ) else {self.split: path_or_paths} lowerCAmelCase = Text( cache_dir=lowercase , data_files=lowercase , features=lowercase , **lowercase , ) def _snake_case ( self ) -> Tuple: # Build iterable dataset if self.streaming: lowerCAmelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None self.builder.download_and_prepare( download_config=lowercase , download_mode=lowercase , verification_mode=lowercase , base_path=lowercase , num_proc=self.num_proc , ) lowerCAmelCase = self.builder.as_dataset( split=self.split , verification_mode=lowercase , in_memory=self.keep_in_memory ) return dataset
46
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = inspect.getfile(accelerate.test_utils ) __a : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __a : Union[str, Any] = test_metrics @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def __UpperCAmelCase ( self ): '''simple docstring''' self.test_metrics.main() @require_multi_gpu def __UpperCAmelCase ( self ): '''simple docstring''' print(f"""Found {torch.cuda.device_count()} devices.""" ) __a : List[Any] = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() )
27
0
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : int ) -> list[str]: """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(_UpperCamelCase ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
47
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): __a : Optional[Any] = tmp_path / 'file.csv' __a : Union[str, Any] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : str = tmp_path / 'malformed_file.csv' __a : int = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = tmp_path / 'csv_with_image.csv' __a : Dict = textwrap.dedent( F"""\ image {image_file} """ ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Union[str, Any] = tmp_path / 'csv_with_label.csv' __a : Any = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Dict = tmp_path / 'csv_with_int_list.csv' __a : Tuple = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): __a : int = Csv() __a : str = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_SCREAMING_SNAKE_CASE , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(_SCREAMING_SNAKE_CASE ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1] __a : Tuple = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) __a : Any = csv._generate_tables([[csv_file_with_image]] ) __a : int = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() __a : Any = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1:] __a : Optional[int] = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) __a : List[str] = csv._generate_tables([[csv_file_with_label]] ) __a : Dict = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() __a : int = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(_SCREAMING_SNAKE_CASE ) for label in labels] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda _SCREAMING_SNAKE_CASE : [int(_SCREAMING_SNAKE_CASE ) for i in x.split()]} ) __a : Any = csv._generate_tables([[csv_file_with_int_list]] ) __a : Any = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) __a : Tuple = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
27
0
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) SCREAMING_SNAKE_CASE__ : List[str] = 'bert-base-cased' SCREAMING_SNAKE_CASE__ : List[Any] = 'fp16' SCREAMING_SNAKE_CASE__ : Optional[Any] = 'bf16' SCREAMING_SNAKE_CASE__ : Union[str, Any] = [FPaa, BFaa] @require_fsdp @require_cuda class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' def _lowercase ( self ) -> Union[str, Any]: super().setUp() lowerCamelCase : int = dict( ACCELERATE_USE_FSDP="true" , MASTER_ADDR="localhost" , MASTER_PORT="10999" , RANK="0" , LOCAL_RANK="0" , WORLD_SIZE="1" , ) def _lowercase ( self ) -> Optional[int]: from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(UpperCamelCase__ ): lowerCamelCase : List[Any] = self.dist_env.copy() lowerCamelCase : Optional[Any] = F'''{i + 1}''' lowerCamelCase : str = strategy with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : Union[str, Any] = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def _lowercase ( self ) -> int: from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(UpperCamelCase__ ): lowerCamelCase : Optional[Any] = self.dist_env.copy() lowerCamelCase : List[str] = prefetch_policy with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : Optional[Any] = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def _lowercase ( self ) -> Tuple: from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(UpperCamelCase__ ): lowerCamelCase : List[str] = self.dist_env.copy() lowerCamelCase : Optional[Any] = state_dict_type with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : List[Any] = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def _lowercase ( self ) -> List[Any]: lowerCamelCase : Optional[int] = AutoModel.from_pretrained(UpperCamelCase__ ) for policy in FSDP_AUTO_WRAP_POLICY: lowerCamelCase : Union[str, Any] = self.dist_env.copy() lowerCamelCase : Tuple = policy if policy == "TRANSFORMER_BASED_WRAP": lowerCamelCase : Dict = "BertLayer" elif policy == "SIZE_BASED_WRAP": lowerCamelCase : Optional[int] = "2000" with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : Union[str, Any] = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(UpperCamelCase__ ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) lowerCamelCase : Optional[Any] = self.dist_env.copy() lowerCamelCase : List[Any] = "TRANSFORMER_BASED_WRAP" lowerCamelCase : List[Any] = "T5Layer" with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : Optional[int] = FullyShardedDataParallelPlugin() with self.assertRaises(UpperCamelCase__ ) as cm: fsdp_plugin.set_auto_wrap_policy(UpperCamelCase__ ) self.assertTrue("Could not find the transformer layer class to wrap in the model." in str(cm.exception ) ) lowerCamelCase : List[Any] = self.dist_env.copy() lowerCamelCase : Any = "SIZE_BASED_WRAP" lowerCamelCase : Tuple = "0" with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : List[str] = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(UpperCamelCase__ ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def _lowercase ( self ) -> Tuple: from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: lowerCamelCase : str = self.dist_env.copy() lowerCamelCase : List[Any] = mp_dtype with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : List[Any] = Accelerator() if mp_dtype == "fp16": lowerCamelCase : Any = torch.floataa elif mp_dtype == "bf16": lowerCamelCase : List[Any] = torch.bfloataa lowerCamelCase : str = MixedPrecision(param_dtype=UpperCamelCase__ , reduce_dtype=UpperCamelCase__ , buffer_dtype=UpperCamelCase__ ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , UpperCamelCase__ ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , UpperCamelCase__ ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(UpperCamelCase__ ) def _lowercase ( self ) -> Tuple: from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: lowerCamelCase : Optional[Any] = self.dist_env.copy() lowerCamelCase : Optional[int] = str(UpperCamelCase__ ).lower() with mockenv_context(**UpperCamelCase__ ): lowerCamelCase : Tuple = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=UpperCamelCase__ ) ) @require_fsdp @require_multi_gpu @slow class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' def _lowercase ( self ) -> Optional[int]: super().setUp() lowerCamelCase : int = 0.82 lowerCamelCase : Any = [ "fsdp_shard_grad_op_transformer_based_wrap", "fsdp_full_shard_transformer_based_wrap", ] lowerCamelCase : Dict = { "multi_gpu_fp16": 3200, "fsdp_shard_grad_op_transformer_based_wrap_fp16": 2000, "fsdp_full_shard_transformer_based_wrap_fp16": 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } lowerCamelCase : int = 160 lowerCamelCase : Optional[int] = 160 lowerCamelCase : List[Any] = inspect.getfile(accelerate.test_utils ) lowerCamelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "external_deps"] ) def _lowercase ( self ) -> Optional[int]: lowerCamelCase : int = os.path.join(self.test_scripts_folder , "test_performance.py" ) lowerCamelCase : Union[str, Any] = ["accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", "--use_fsdp"] for config in self.performance_configs: lowerCamelCase : int = cmd.copy() for i, strategy in enumerate(UpperCamelCase__ ): if strategy.lower() in config: cmd_config.append(F'''--fsdp_sharding_strategy={i+1}''' ) break if "fp32" in config: cmd_config.append("--mixed_precision=no" ) else: cmd_config.append("--mixed_precision=fp16" ) if "cpu_offload" in config: cmd_config.append("--fsdp_offload_params=True" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("--fsdp_min_num_params=2000" ) cmd_config.extend( [ self.test_file_path, F'''--output_dir={self.tmpdir}''', F'''--performance_lower_bound={self.performance_lower_bound}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) def _lowercase ( self ) -> Any: lowerCamelCase : List[str] = os.path.join(self.test_scripts_folder , "test_checkpointing.py" ) lowerCamelCase : List[str] = [ "accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", "--use_fsdp", "--mixed_precision=fp16", "--fsdp_transformer_layer_cls_to_wrap=BertLayer", ] for i, strategy in enumerate(UpperCamelCase__ ): lowerCamelCase : str = cmd.copy() cmd_config.append(F'''--fsdp_sharding_strategy={i+1}''' ) if strategy != "FULL_SHARD": continue lowerCamelCase : Dict = len(UpperCamelCase__ ) for state_dict_type in FSDP_STATE_DICT_TYPE: lowerCamelCase : List[str] = cmd_config[:state_dict_config_index] cmd_config.append(F'''--fsdp_state_dict_type={state_dict_type}''' ) cmd_config.extend( [ self.test_file_path, F'''--output_dir={self.tmpdir}''', "--partial_train_epoch=1", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) lowerCamelCase : Dict = cmd_config[:-1] lowerCamelCase : Dict = os.path.join(self.tmpdir , "epoch_0" ) cmd_config.extend( [ F'''--resume_from_checkpoint={resume_from_checkpoint}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) def _lowercase ( self ) -> Tuple: lowerCamelCase : int = os.path.join(self.test_scripts_folder , "test_peak_memory_usage.py" ) lowerCamelCase : Tuple = [ "accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): lowerCamelCase : str = cmd.copy() if "fp16" in spec: cmd_config.extend(["--mixed_precision=fp16"] ) else: cmd_config.extend(["--mixed_precision=no"] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["--use_fsdp"] ) for i, strategy in enumerate(UpperCamelCase__ ): if strategy.lower() in spec: cmd_config.append(F'''--fsdp_sharding_strategy={i+1}''' ) break if "cpu_offload" in spec: cmd_config.append("--fsdp_offload_params=True" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("--fsdp_min_num_params=2000" ) cmd_config.extend( [ self.test_file_path, F'''--output_dir={self.tmpdir}''', F'''--peak_memory_upper_bound={peak_mem_upper_bound}''', F'''--n_train={self.n_train}''', F'''--n_val={self.n_val}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() )
48
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Union[str, Any] = { 'configuration_blenderbot': [ 'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotConfig', 'BlenderbotOnnxConfig', ], 'tokenization_blenderbot': ['BlenderbotTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ['BlenderbotTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = [ 'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotForCausalLM', 'BlenderbotForConditionalGeneration', 'BlenderbotModel', 'BlenderbotPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ 'TFBlenderbotForConditionalGeneration', 'TFBlenderbotModel', 'TFBlenderbotPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Dict = [ 'FlaxBlenderbotForConditionalGeneration', 'FlaxBlenderbotModel', 'FlaxBlenderbotPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case :Union[str, Any] = logging.get_logger(__name__) __snake_case :Any = { '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''', } class _A ( __UpperCAmelCase ): UpperCamelCase__ : Optional[int] = '''switch_transformers''' UpperCamelCase__ : Optional[Any] = ['''past_key_values'''] UpperCamelCase__ : Optional[Any] = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str=32_128 , __SCREAMING_SNAKE_CASE : int=768 , __SCREAMING_SNAKE_CASE : Any=64 , __SCREAMING_SNAKE_CASE : Optional[int]=2_048 , __SCREAMING_SNAKE_CASE : List[str]=64 , __SCREAMING_SNAKE_CASE : int=12 , __SCREAMING_SNAKE_CASE : Any=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=12 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , __SCREAMING_SNAKE_CASE : Any=12 , __SCREAMING_SNAKE_CASE : Tuple=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.01 , __SCREAMING_SNAKE_CASE : Dict="float32" , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=32 , __SCREAMING_SNAKE_CASE : int=128 , __SCREAMING_SNAKE_CASE : Any=0.1 , __SCREAMING_SNAKE_CASE : int=1E-6 , __SCREAMING_SNAKE_CASE : Dict=0.0_01 , __SCREAMING_SNAKE_CASE : List[str]=0.0_01 , __SCREAMING_SNAKE_CASE : List[Any]=1.0 , __SCREAMING_SNAKE_CASE : Optional[int]="relu" , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : int=0 , __SCREAMING_SNAKE_CASE : List[Any]=1 , **__SCREAMING_SNAKE_CASE : Dict , ): '''simple docstring''' __a = vocab_size __a = d_model __a = d_kv __a = d_ff __a = num_sparse_encoder_layers __a = num_layers __a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __a = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: __a = self.num_layers // self.num_sparse_encoder_layers else: __a = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: __a = self.num_decoder_layers // self.num_sparse_decoder_layers else: __a = self.num_decoder_layers # HACK: this will create 0 sparse layers __a = num_heads __a = num_experts __a = expert_capacity __a = router_bias __a = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}') __a = router_dtype __a = router_ignore_padding_tokens __a = relative_attention_num_buckets __a = relative_attention_max_distance __a = dropout_rate __a = layer_norm_epsilon __a = initializer_factor __a = feed_forward_proj __a = use_cache __a = add_router_probs __a = router_z_loss_coef __a = router_aux_loss_coef __a = self.feed_forward_proj.split('''-''') __a = act_info[-1] __a = act_info[0] == '''gated''' if len(__SCREAMING_SNAKE_CASE) > 1 and act_info[0] != "gated" or len(__SCREAMING_SNAKE_CASE) > 2: raise ValueError( F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''') # for backwards compatibility if feed_forward_proj == "gated-gelu": __a = '''gelu_new''' super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , )
49
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase : def __init__( self , __a , __a=2 , __a=3 , __a=4 , __a=2 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=36 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=6 , __a=6 , __a=3 , __a=4 , __a=None , __a=1000 , ): '''simple docstring''' __a : Optional[Any] = parent __a : int = batch_size __a : Any = num_channels __a : Optional[int] = image_size __a : Dict = patch_size __a : int = is_training __a : Union[str, Any] = use_input_mask __a : Optional[int] = use_token_type_ids __a : Dict = use_labels __a : str = vocab_size __a : List[Any] = hidden_size __a : Union[str, Any] = num_hidden_layers __a : str = num_attention_heads __a : Union[str, Any] = intermediate_size __a : Any = hidden_act __a : List[str] = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : List[Any] = max_position_embeddings __a : Tuple = type_vocab_size __a : Any = type_sequence_label_size __a : Optional[int] = initializer_range __a : Any = coordinate_size __a : List[Any] = shape_size __a : Optional[int] = num_labels __a : Dict = num_choices __a : Union[str, Any] = scope __a : Union[str, Any] = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __a : Optional[int] = text_seq_length __a : Any = (image_size // patch_size) ** 2 + 1 __a : Dict = self.text_seq_length + self.image_seq_length def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __a : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __a : Any = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a : List[Any] = bbox[i, j, 3] __a : Tuple = bbox[i, j, 1] __a : str = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __a : int = bbox[i, j, 2] __a : Dict = bbox[i, j, 0] __a : int = tmp_coordinate __a : Optional[int] = tf.constant(__a ) __a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_input_mask: __a : Optional[Any] = random_attention_mask([self.batch_size, self.text_seq_length] ) __a : str = None if self.use_token_type_ids: __a : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __a : Optional[Any] = None __a : Optional[int] = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __a : int = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = TFLayoutLMvaModel(config=__a ) # text + image __a : List[Any] = model(__a , pixel_values=__a , training=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , training=__a , ) __a : Optional[int] = model(__a , bbox=__a , pixel_values=__a , training=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __a : Any = model(__a , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __a : str = model({'pixel_values': pixel_values} , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = TFLayoutLMvaForSequenceClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : str = self.num_labels __a : Optional[Any] = TFLayoutLMvaForTokenClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[Any] = 2 __a : Any = TFLayoutLMvaForQuestionAnswering(config=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , training=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a)) : Dict = config_and_inputs __a : Any = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) A_ = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) A_ = False A_ = False A_ = False def __UpperCAmelCase ( self , __a , __a , __a , __a , __a ): '''simple docstring''' return True def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : str = copy.deepcopy(__a ) if model_class in get_values(__a ): __a : str = { k: tf.tile(tf.expand_dims(__a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(__a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__a ): __a : Optional[int] = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : int = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __a : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Union[str, Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = TFLayoutLMvaModelTester(self ) __a : Optional[int] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) if getattr(__a , 'hf_compute_loss' , __a ): # The number of elements in the loss should be the same as the number of elements in the label __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=__a )[0] ] __a : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : Dict = prepared_for_class.pop('input_ids' ) __a : Tuple = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __a : Union[str, Any] = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __a : List[Any] = -100 __a : List[str] = tf.convert_to_tensor(__a ) __a : Any = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = model(__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __a : Tuple = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) # Get keys that were added with the _prepare_for_class function __a : Dict = prepared_for_class.keys() - inputs_dict.keys() __a : Any = inspect.signature(model.call ).parameters __a : str = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __a : List[Any] = {0: 'input_ids'} for label_key in label_keys: __a : List[Any] = signature_names.index(__a ) __a : Union[str, Any] = label_key __a : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __a : Union[str, Any] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __a : Optional[Any] = prepared_for_class[value] __a : str = tuple(__a ) # Send to model __a : Tuple = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a : Any = type self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( __a , __a , __a , __a , __a , __a , __a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = TFLayoutLMvaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__a ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __a : Tuple = self.default_image_processor __a : List[Any] = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ).pixel_values __a : Union[str, Any] = tf.constant([[1, 2]] ) __a : Optional[Any] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __a : Tuple = model(input_ids=__a , bbox=__a , pixel_values=__a , training=__a ) # verify the logits __a : List[Any] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , __a ) __a : Optional[Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , __a , atol=1E-4 ) )
27
0
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowerCAmelCase ( unittest.TestCase ): def A_ ( self : int ) -> Optional[Any]: debug_launcher(test_script.main ) def A_ ( self : List[str] ) -> Optional[int]: debug_launcher(test_ops.main )
50
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"""{test_file} instead.""" ) __a : Tuple = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __a : List[str] = components[:-1] + [test_fn.replace('.py' , '' )] __a : Optional[Any] = '.'.join(_SCREAMING_SNAKE_CASE ) return test_module_path def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = get_module_path(_SCREAMING_SNAKE_CASE ) __a : Dict = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = [] __a : List[str] = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : Any = [] __a : str = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): __a : int = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'all_model_classes' , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Tuple = test_class() if hasattr(_SCREAMING_SNAKE_CASE , 'setUp' ): test.setUp() __a : List[Any] = None if hasattr(_SCREAMING_SNAKE_CASE , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __a : List[str] = test.model_tester.__class__ return model_tester def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] ): __a : List[Any] = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [] for test_class in test_classes: __a : Any = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : str = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
27
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) snake_case_ : Optional[Any] = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Dict = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys snake_case_ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = StableDiffusionInpaintPipeline A_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS A_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS A_ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess A_ = frozenset([] ) def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__a , ) __a : str = PNDMScheduler(skip_prk_steps=__a ) torch.manual_seed(0 ) __a : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __a : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __a : Dict = CLIPTextModel(__a ) __a : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __a : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCAmelCase ( self , __a , __a=0 ): '''simple docstring''' __a : Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) __a : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a : Tuple = Image.fromarray(np.uinta(__a ) ).convert('RGB' ).resize((64, 64) ) __a : Tuple = Image.fromarray(np.uinta(image + 4 ) ).convert('RGB' ).resize((64, 64) ) if str(__a ).startswith('mps' ): __a : Any = torch.manual_seed(__a ) else: __a : str = torch.Generator(device=__a ).manual_seed(__a ) __a : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': init_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator __a : str = self.get_dummy_components() __a : Union[str, Any] = StableDiffusionInpaintPipeline(**__a ) __a : List[Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) __a : List[Any] = self.get_dummy_inputs(__a ) __a : Dict = sd_pipe(**__a ).images __a : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : List[Any] = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench.npy' ) __a : Optional[int] = 'stabilityai/stable-diffusion-2-inpainting' __a : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained(__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Dict = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : int = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench_fp16.npy' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : List[str] = StableDiffusionInpaintPipeline.from_pretrained( __a , torch_dtype=torch.floataa , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Union[str, Any] = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : int = torch.manual_seed(0 ) __a : Optional[Any] = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : int = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def __UpperCAmelCase ( self ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __a : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : Any = PNDMScheduler.from_pretrained(__a , subfolder='scheduler' ) __a : str = StableDiffusionInpaintPipeline.from_pretrained( __a , safety_checker=__a , scheduler=__a , torch_dtype=torch.floataa , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __a : str = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : str = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , num_inference_steps=2 , output_type='np' , ) __a : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
27
0
import pprint import requests __lowerCamelCase : Tuple = """https://zenquotes.io/api""" def A_ ( ) -> list: return requests.get(API_ENDPOINT_URL + "/today" ).json() def A_ ( ) -> list: return requests.get(API_ENDPOINT_URL + "/random" ).json() if __name__ == "__main__": __lowerCamelCase : Optional[int] = random_quotes() pprint.pprint(response)
52
'''simple docstring''' import requests __lowercase : Tuple = '' # <-- Put your OpenWeatherMap appid here! __lowercase : Tuple = 'https://api.openweathermap.org/data/2.5/' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Chicago" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'weather' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Kolkata, India" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : float = 5_5.6_8 , _SCREAMING_SNAKE_CASE : float = 1_2.5_7 , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowercase : Dict = input('Enter a location:').strip() if location: pprint(current_weather(location)) else: break
27
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL a__ : List[str] =logging.get_logger(__name__) def lowercase__ ( __lowercase : str , __lowercase : List[Any] ) -> Dict: """simple docstring""" __UpperCamelCase = b.T __UpperCamelCase = np.sum(np.square(__lowercase ) , axis=1 ) __UpperCamelCase = np.sum(np.square(__lowercase ) , axis=0 ) __UpperCamelCase = np.matmul(__lowercase , __lowercase ) __UpperCamelCase = aa[:, None] - 2 * ab + ba[None, :] return d def lowercase__ ( __lowercase : Tuple , __lowercase : Dict ) -> List[Any]: """simple docstring""" __UpperCamelCase = x.reshape(-1 , 3 ) __UpperCamelCase = squared_euclidean_distance(__lowercase , __lowercase ) return np.argmin(__lowercase , axis=1 ) class snake_case ( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] =["pixel_values"] def __init__( self : Union[str, Any] , __A : Optional[Union[List[List[int]], np.ndarray]] = None , __A : bool = True , __A : Dict[str, int] = None , __A : PILImageResampling = PILImageResampling.BILINEAR , __A : bool = True , __A : bool = True , **__A : List[str] , ): super().__init__(**__A ) __UpperCamelCase = size if size is not None else {'height': 2_5_6, 'width': 2_5_6} __UpperCamelCase = get_size_dict(__A ) __UpperCamelCase = np.array(__A ) if clusters is not None else None __UpperCamelCase = do_resize __UpperCamelCase = size __UpperCamelCase = resample __UpperCamelCase = do_normalize __UpperCamelCase = do_color_quantize def _lowerCamelCase ( self : Optional[int] , __A : np.ndarray , __A : Dict[str, int] , __A : PILImageResampling = PILImageResampling.BILINEAR , __A : Optional[Union[str, ChannelDimension]] = None , **__A : Union[str, Any] , ): __UpperCamelCase = get_size_dict(__A ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( __A , size=(size['height'], size['width']) , resample=__A , data_format=__A , **__A ) def _lowerCamelCase ( self : Dict , __A : np.ndarray , __A : Optional[Union[str, ChannelDimension]] = None , ): __UpperCamelCase = rescale(image=__A , scale=1 / 127.5 , data_format=__A ) __UpperCamelCase = image - 1 return image def _lowerCamelCase ( self : Optional[Any] , __A : ImageInput , __A : bool = None , __A : Dict[str, int] = None , __A : PILImageResampling = None , __A : bool = None , __A : Optional[bool] = None , __A : Optional[Union[List[List[int]], np.ndarray]] = None , __A : Optional[Union[str, TensorType]] = None , __A : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **__A : Optional[int] , ): __UpperCamelCase = do_resize if do_resize is not None else self.do_resize __UpperCamelCase = size if size is not None else self.size __UpperCamelCase = get_size_dict(__A ) __UpperCamelCase = resample if resample is not None else self.resample __UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase = do_color_quantize if do_color_quantize is not None else self.do_color_quantize __UpperCamelCase = clusters if clusters is not None else self.clusters __UpperCamelCase = np.array(__A ) __UpperCamelCase = make_list_of_images(__A ) if not valid_images(__A ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. __UpperCamelCase = [to_numpy_array(__A ) for image in images] if do_resize: __UpperCamelCase = [self.resize(image=__A , size=__A , resample=__A ) for image in images] if do_normalize: __UpperCamelCase = [self.normalize(image=__A ) for image in images] if do_color_quantize: __UpperCamelCase = [to_channel_dimension_format(__A , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) __UpperCamelCase = np.array(__A ) __UpperCamelCase = color_quantize(__A , __A ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) __UpperCamelCase = images.shape[0] __UpperCamelCase = images.reshape(__A , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. __UpperCamelCase = list(__A ) else: __UpperCamelCase = [to_channel_dimension_format(__A , __A ) for image in images] __UpperCamelCase = {'input_ids': images} return BatchFeature(data=__A , tensor_type=__A )
53
'''simple docstring''' import torch from transformers import AutoModel class __UpperCamelCase ( torch.nn.Module ): def __init__( self , __a="sayef/fsner-bert-base-uncased" ): '''simple docstring''' super(__a , self ).__init__() __a : Tuple = AutoModel.from_pretrained(__a , return_dict=__a ) __a : int = torch.nn.CosineSimilarity(3 , 1E-0_8 ) __a : Union[str, Any] = torch.nn.Softmax(dim=1 ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return self.bert(**__a ).last_hidden_state def __UpperCAmelCase ( self , __a ): '''simple docstring''' return token_embeddings.sum(2 , keepdim=__a ) def __UpperCAmelCase ( self , __a , __a , __a=1 ): '''simple docstring''' return self.softmax(T * self.cos(__a , __a ) ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : str = W_supports['sizes'].tolist() __a : Union[str, Any] = W_supports['start_token_id'].item() __a : Any = W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __a : Tuple = self.BERT(**__a ) __a : str = self.BERT(**__a ) __a : Any = None __a : Dict = None __a : Dict = W_supports['input_ids'] == start_token_id __a : Union[str, Any] = W_supports['input_ids'] == end_token_id for i, size in enumerate(__a ): if i == 0: __a : Optional[int] = 0 else: __a : Union[str, Any] = support_sizes[i - 1] __a : int = S[s : s + size][start_token_masks[s : s + size]] __a : Union[str, Any] = S[s : s + size][end_token_masks[s : s + size]] __a : Tuple = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __a : Dict = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __a : str = torch.vstack((p_starts, p_start) ) __a : str = torch.vstack((p_ends, p_end) ) else: __a : List[str] = p_start __a : int = p_end return p_starts, p_ends
27
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : List[Any] = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 35 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : Optional[Any] = x_den * y_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : Optional[int] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : List[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Any = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Optional[int] = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 __a : int = x_num * y_num __a : Optional[Any] = x_den * y_num + x_num * y_den __a : Tuple = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : List[Any] = x_num * x_num * y_num * y_num __a : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : Optional[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
27
0
'''simple docstring''' from __future__ import annotations a_ : int = """#""" class snake_case : """simple docstring""" def __init__( self ): """simple docstring""" lowerCamelCase_ = {} def snake_case ( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self._trie for char in text: if char not in trie: lowerCamelCase_ = {} lowerCamelCase_ = trie[char] lowerCamelCase_ = True def snake_case ( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self._trie for char in prefix: if char in trie: lowerCamelCase_ = trie[char] else: return [] return self._elements(UpperCamelCase ) def snake_case ( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = [] for c, v in d.items(): lowerCamelCase_ = [" "] if c == END else [(c + s) for s in self._elements(UpperCamelCase )] result.extend(UpperCamelCase ) return tuple(UpperCamelCase ) a_ : Any = Trie() a_ : Dict = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def __snake_case ( UpperCAmelCase_ : str ): lowerCamelCase_ = trie.find_word(UpperCAmelCase_ ) return tuple(string + word for word in suffixes ) def __snake_case ( ): print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
55
'''simple docstring''' import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): @property def __UpperCAmelCase ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ort.SessionOptions() __a : Dict = False return options def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) __a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default __a : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__a , feature_extractor=__a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__a ) __a : Tuple = 'A red cat sitting on a park bench' __a : int = np.random.RandomState(0 ) __a : Tuple = pipe( prompt=__a , image=__a , mask_image=__a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=__a , output_type='np' , ) __a : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
27
0
'''simple docstring''' from __future__ import annotations import math def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> list: '''simple docstring''' if len(__UpperCAmelCase ) != 2 or len(a[0] ) != 2 or len(__UpperCAmelCase ) != 2 or len(b[0] ) != 2: raise Exception('''Matrices are not 2x2''' ) snake_case_ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Any: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__UpperCAmelCase ) ) ] def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> int: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__UpperCAmelCase ) ) ] def __magic_name__ ( __UpperCAmelCase ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__UpperCAmelCase ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('''Odd matrices are not supported!''' ) snake_case_ = len(__UpperCAmelCase ) snake_case_ = matrix_length // 2 snake_case_ = [[a[i][j] for j in range(__UpperCAmelCase, __UpperCAmelCase )] for i in range(__UpperCAmelCase )] snake_case_ = [ [a[i][j] for j in range(__UpperCAmelCase, __UpperCAmelCase )] for i in range(__UpperCAmelCase, __UpperCAmelCase ) ] snake_case_ = [[a[i][j] for j in range(__UpperCAmelCase )] for i in range(__UpperCAmelCase )] snake_case_ = [[a[i][j] for j in range(__UpperCAmelCase )] for i in range(__UpperCAmelCase, __UpperCAmelCase )] return top_left, top_right, bot_left, bot_right def __magic_name__ ( __UpperCAmelCase ) -> tuple[int, int]: '''simple docstring''' return len(__UpperCAmelCase ), len(matrix[0] ) def __magic_name__ ( __UpperCAmelCase ) -> None: '''simple docstring''' print('''\n'''.join(str(__UpperCAmelCase ) for line in matrix ) ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> list: '''simple docstring''' if matrix_dimensions(__UpperCAmelCase ) == (2, 2): return default_matrix_multiplication(__UpperCAmelCase, __UpperCAmelCase ) snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = split_matrix(__UpperCAmelCase ) snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = split_matrix(__UpperCAmelCase ) snake_case_ = actual_strassen(__UpperCAmelCase, matrix_subtraction(__UpperCAmelCase, __UpperCAmelCase ) ) snake_case_ = actual_strassen(matrix_addition(__UpperCAmelCase, __UpperCAmelCase ), __UpperCAmelCase ) snake_case_ = actual_strassen(matrix_addition(__UpperCAmelCase, __UpperCAmelCase ), __UpperCAmelCase ) snake_case_ = actual_strassen(__UpperCAmelCase, matrix_subtraction(__UpperCAmelCase, __UpperCAmelCase ) ) snake_case_ = actual_strassen(matrix_addition(__UpperCAmelCase, __UpperCAmelCase ), matrix_addition(__UpperCAmelCase, __UpperCAmelCase ) ) snake_case_ = actual_strassen(matrix_subtraction(__UpperCAmelCase, __UpperCAmelCase ), matrix_addition(__UpperCAmelCase, __UpperCAmelCase ) ) snake_case_ = actual_strassen(matrix_subtraction(__UpperCAmelCase, __UpperCAmelCase ), matrix_addition(__UpperCAmelCase, __UpperCAmelCase ) ) snake_case_ = matrix_addition(matrix_subtraction(matrix_addition(__UpperCAmelCase, __UpperCAmelCase ), __UpperCAmelCase ), __UpperCAmelCase ) snake_case_ = matrix_addition(__UpperCAmelCase, __UpperCAmelCase ) snake_case_ = matrix_addition(__UpperCAmelCase, __UpperCAmelCase ) snake_case_ = matrix_subtraction(matrix_subtraction(matrix_addition(__UpperCAmelCase, __UpperCAmelCase ), __UpperCAmelCase ), __UpperCAmelCase ) # construct the new matrix from our 4 quadrants snake_case_ = [] for i in range(len(__UpperCAmelCase ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__UpperCAmelCase ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> list: '''simple docstring''' if matrix_dimensions(__UpperCAmelCase )[1] != matrix_dimensions(__UpperCAmelCase )[0]: snake_case_ = ( '''Unable to multiply these matrices, please check the dimensions.\n''' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(__UpperCAmelCase ) snake_case_ = matrix_dimensions(__UpperCAmelCase ) snake_case_ = matrix_dimensions(__UpperCAmelCase ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] snake_case_ = max(*__UpperCAmelCase, *__UpperCAmelCase ) snake_case_ = int(math.pow(2, math.ceil(math.loga(__UpperCAmelCase ) ) ) ) snake_case_ = matrixa snake_case_ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0, __UpperCAmelCase ): if i < dimensiona[0]: for _ in range(dimensiona[1], __UpperCAmelCase ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1], __UpperCAmelCase ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) snake_case_ = actual_strassen(__UpperCAmelCase, __UpperCAmelCase ) # Removing the additional zeros for i in range(0, __UpperCAmelCase ): if i < dimensiona[0]: for _ in range(dimensiona[1], __UpperCAmelCase ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a : List[Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a : Union[str, Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
56
'''simple docstring''' import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowercase : Dict = 16 __lowercase : List[Any] = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return int(x / 2**20 ) class __UpperCamelCase : def __enter__( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero __a : Optional[int] = torch.cuda.memory_allocated() return self def __exit__( self , *__a ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() __a : Dict = torch.cuda.memory_allocated() __a : List[Any] = torch.cuda.max_memory_allocated() __a : Tuple = bamb(self.end - self.begin ) __a : Tuple = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def lowerCamelCase (_SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : int = 16 , _SCREAMING_SNAKE_CASE : str = "bert-base-cased" , _SCREAMING_SNAKE_CASE : int = 320 , _SCREAMING_SNAKE_CASE : int = 160 , ): __a : int = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : List[Any] = load_dataset( 'glue' , 'mrpc' , split={'train': F"""train[:{n_train}]""", 'validation': F"""validation[:{n_val}]"""} ) def tokenize_function(_SCREAMING_SNAKE_CASE : Tuple ): # max_length=None => use the model max length (it's actually the default) __a : Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a : List[str] = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=_SCREAMING_SNAKE_CASE ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : Tuple = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. __a : int = DataLoader( tokenized_datasets['train'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) __a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): # Initialize accelerator __a : str = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : Dict = config['lr'] __a : str = int(config['num_epochs'] ) __a : Optional[int] = int(config['seed'] ) __a : Any = int(config['batch_size'] ) __a : List[str] = args.model_name_or_path set_seed(_SCREAMING_SNAKE_CASE ) __a , __a : int = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : Optional[int] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE ) # Instantiate optimizer __a : Optional[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a : Optional[Any] = optimizer_cls(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) if accelerator.state.deepspeed_plugin is not None: __a : int = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: __a : Union[str, Any] = 1 __a : Tuple = (len(_SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a : str = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=0 , num_training_steps=_SCREAMING_SNAKE_CASE , ) else: __a : List[Any] = DummyScheduler(_SCREAMING_SNAKE_CASE , total_num_steps=_SCREAMING_SNAKE_CASE , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a : Optional[Any] = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # We need to keep track of how many total steps we have iterated over __a : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly __a : Dict = 0 # Now we train the model __a : str = {} for epoch in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): __a : List[Any] = model(**_SCREAMING_SNAKE_CASE ) __a : str = outputs.loss __a : str = loss / gradient_accumulation_steps accelerator.backward(_SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin ) ) ) accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used ) ) accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked ) ) accelerator.print( 'Total Peak Memory consumed during the train (max): {}'.format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) __a : List[Any] = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'peak_memory_utilization.json' ) , 'w' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : int = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=_SCREAMING_SNAKE_CASE , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_SCREAMING_SNAKE_CASE , ) parser.add_argument( '--output_dir' , type=_SCREAMING_SNAKE_CASE , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--peak_memory_upper_bound' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.' , ) parser.add_argument( '--n_train' , type=_SCREAMING_SNAKE_CASE , default=320 , help='Number of training examples to use.' , ) parser.add_argument( '--n_val' , type=_SCREAMING_SNAKE_CASE , default=160 , help='Number of validation examples to use.' , ) parser.add_argument( '--num_epochs' , type=_SCREAMING_SNAKE_CASE , default=1 , help='Number of train epochs.' , ) __a : List[str] = parser.parse_args() __a : List[Any] = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
27
0
"""simple docstring""" import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" __lowerCAmelCase = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert("RGB" ) __lowerCAmelCase = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73) , (0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11) ), ] ) __lowerCAmelCase = transform(_UpperCamelCase ).unsqueeze(0 ).to(_UpperCamelCase ) return image def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' if "visual_encoder" in key: __lowerCAmelCase = re.sub("visual_encoder*" , "vision_model.encoder" , _UpperCamelCase ) if "blocks" in key: __lowerCAmelCase = re.sub(R"blocks" , "layers" , _UpperCamelCase ) if "attn" in key: __lowerCAmelCase = re.sub(R"attn" , "self_attn" , _UpperCamelCase ) if "norm1" in key: __lowerCAmelCase = re.sub(R"norm1" , "layer_norm1" , _UpperCamelCase ) if "norm2" in key: __lowerCAmelCase = re.sub(R"norm2" , "layer_norm2" , _UpperCamelCase ) if "encoder.norm" in key: __lowerCAmelCase = re.sub(R"encoder.norm" , "post_layernorm" , _UpperCamelCase ) if "encoder.patch_embed.proj" in key: __lowerCAmelCase = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , _UpperCamelCase ) if "encoder.pos_embed" in key: __lowerCAmelCase = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , _UpperCamelCase ) if "encoder.cls_token" in key: __lowerCAmelCase = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , _UpperCamelCase ) if "self_attn" in key: __lowerCAmelCase = re.sub(R"self_attn.proj" , "self_attn.projection" , _UpperCamelCase ) return key @torch.no_grad() def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=None ): '''simple docstring''' if config_path is not None: __lowerCAmelCase = BlipConfig.from_pretrained(_UpperCamelCase ) else: __lowerCAmelCase = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) __lowerCAmelCase = BlipForConditionalGeneration(_UpperCamelCase ).eval() __lowerCAmelCase = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" __lowerCAmelCase = blip_decoder(pretrained=_UpperCamelCase , image_size=384 , vit="base" ) __lowerCAmelCase = pt_model.eval() __lowerCAmelCase = pt_model.state_dict() for key in modified_state_dict.copy(): __lowerCAmelCase = modified_state_dict.pop(_UpperCamelCase ) __lowerCAmelCase = rename_key(_UpperCamelCase ) __lowerCAmelCase = value hf_model.load_state_dict(_UpperCamelCase ) __lowerCAmelCase = 384 __lowerCAmelCase = load_demo_image(image_size=_UpperCamelCase , device="cpu" ) __lowerCAmelCase = BertTokenizer.from_pretrained("bert-base-uncased" ) __lowerCAmelCase = tokenizer(["a picture of"] ).input_ids __lowerCAmelCase = hf_model.generate(_UpperCamelCase , _UpperCamelCase ) assert out[0].tolist() == [3_0522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] __lowerCAmelCase = hf_model.generate(_UpperCamelCase ) assert out[0].tolist() == [3_0522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_UpperCamelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' __lowerCAmelCase = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) __lowerCAmelCase = blip_vqa(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit="base" ) vqa_model.eval() __lowerCAmelCase = vqa_model.state_dict() for key in modified_state_dict.copy(): __lowerCAmelCase = modified_state_dict.pop(_UpperCamelCase ) __lowerCAmelCase = rename_key(_UpperCamelCase ) __lowerCAmelCase = value __lowerCAmelCase = BlipForQuestionAnswering(_UpperCamelCase ) hf_vqa_model.load_state_dict(_UpperCamelCase ) __lowerCAmelCase = ["How many dogs are in this image?"] __lowerCAmelCase = tokenizer(_UpperCamelCase , return_tensors="pt" ).input_ids __lowerCAmelCase = hf_vqa_model.generate(_UpperCamelCase , _UpperCamelCase ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) __lowerCAmelCase = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" __lowerCAmelCase = blip_itm(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit="base" ) itm_model.eval() __lowerCAmelCase = itm_model.state_dict() for key in modified_state_dict.copy(): __lowerCAmelCase = modified_state_dict.pop(_UpperCamelCase ) __lowerCAmelCase = rename_key(_UpperCamelCase ) __lowerCAmelCase = value __lowerCAmelCase = BlipForImageTextRetrieval(_UpperCamelCase ) __lowerCAmelCase = ["A picture of a woman with a dog sitting in a beach"] __lowerCAmelCase = tokenizer( _UpperCamelCase , return_tensors="pt" , padding="max_length" , truncation=_UpperCamelCase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_UpperCamelCase ) hf_itm_model.eval() __lowerCAmelCase = hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) __lowerCAmelCase = hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) assert out[0].item() == 0.21_10_68_74_94_27_79_54 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_56_98_84_53_86_50_51_27 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": A : Optional[int] = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") A : Optional[int] = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
57
'''simple docstring''' import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer __lowercase : List[Any] = 'bart' __lowercase : Union[str, Any] = True @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : List[Any] = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) __a : Dict = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) __a : Optional[int] = qar_model.eval() else: __a , __a : str = (None, None) if MODEL_TYPE == "bart": __a : Union[str, Any] = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) __a : int = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) __a : Optional[Any] = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) __a : str = sas_model.eval() else: __a , __a : Tuple = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : Optional[Any] = faiss.StandardGpuResources() __a : Dict = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] __a : int = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 128) , ) __a : int = faiss.IndexFlatIP(128 ) __a : Any = faiss.index_cpu_to_gpu(_SCREAMING_SNAKE_CASE , 1 , _SCREAMING_SNAKE_CASE ) wikiaab_gpu_index_flat.add(_SCREAMING_SNAKE_CASE ) # TODO fix for larger GPU else: __a , __a : str = (None, None) __a : Optional[int] = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : Dict = datasets.load_dataset('eli5' , name='LFQA_reddit' ) __a : Dict = elia['train_eli5'] __a : Optional[int] = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 128) ) __a : str = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(_SCREAMING_SNAKE_CASE ) return (elia_train, eli5_train_q_index) __lowercase , __lowercase , __lowercase : Any = load_indexes() __lowercase , __lowercase , __lowercase , __lowercase : Dict = load_models() __lowercase , __lowercase : int = load_train_data() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str]=10 ): __a : Optional[int] = embed_questions_for_retrieval([question] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a , __a : Union[str, Any] = eli5_train_q_index.search(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [elia_train[int(_SCREAMING_SNAKE_CASE )] for i in I[0]] return nn_examples def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : str="wiki40b" , _SCREAMING_SNAKE_CASE : List[str]="dense" , _SCREAMING_SNAKE_CASE : Any=10 ): if source == "none": __a , __a : Any = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": __a , __a : str = query_qa_dense_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a , __a : Union[str, Any] = query_es_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index_name='english_wiki40b_snippets_100w' , n_results=_SCREAMING_SNAKE_CASE , ) __a : Dict = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] __a : Any = 'question: {} context: {}'.format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda _SCREAMING_SNAKE_CASE : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _SCREAMING_SNAKE_CASE : None), } ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Dict=64 , _SCREAMING_SNAKE_CASE : Dict=256 , _SCREAMING_SNAKE_CASE : Any=False , _SCREAMING_SNAKE_CASE : Tuple=2 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0.9_5 , _SCREAMING_SNAKE_CASE : str=0.8 ): with torch.no_grad(): __a : Union[str, Any] = qa_sas_generate( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , num_answers=1 , num_beams=_SCREAMING_SNAKE_CASE , min_len=_SCREAMING_SNAKE_CASE , max_len=_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE , temp=_SCREAMING_SNAKE_CASE , top_p=_SCREAMING_SNAKE_CASE , top_k=_SCREAMING_SNAKE_CASE , max_input_length=1_024 , device='cuda:0' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar __lowercase : Optional[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' __lowercase : str = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia __lowercase : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) __lowercase : Dict = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] __lowercase : Union[str, Any] = st.sidebar.checkbox('Demo options') if demo_options: __lowercase : Any = st.sidebar.selectbox( '', action_list, index=3, ) __lowercase : Tuple = action_list.index(action_st) __lowercase : Tuple = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) __lowercase : List[Any] = show_type == 'Show full text of passages' else: __lowercase : int = 3 __lowercase : str = True __lowercase : Tuple = st.sidebar.checkbox('Retrieval options') if retrieval_options: __lowercase : List[Any] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: __lowercase : str = 'wiki40b' __lowercase : List[Any] = 'dense' __lowercase : Dict = 'beam' __lowercase : Optional[int] = 2 __lowercase : List[str] = 64 __lowercase : Tuple = 2_56 __lowercase : List[str] = None __lowercase : Tuple = None __lowercase : List[Any] = st.sidebar.checkbox('Generation options') if generate_options: __lowercase : Optional[Any] = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) __lowercase : List[Any] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) __lowercase : Tuple = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=2_56, value=64, step=8, format=None, key=None ) __lowercase : int = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None ) if sampled == "beam": __lowercase : Any = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: __lowercase : Dict = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) __lowercase : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) __lowercase : List[str] = None # start main text __lowercase : int = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] __lowercase : Optional[int] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": __lowercase : Any = st.text_input('Enter your question here:', '') else: __lowercase : Any = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": __lowercase , __lowercase : Optional[int] = make_support(question, source=wiki_source, method='dense', n_results=10) __lowercase , __lowercase : List[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) __lowercase : Optional[int] = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] __lowercase : str = support_list[:10] __lowercase : Optional[int] = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: __lowercase , __lowercase : Optional[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: __lowercase , __lowercase : int = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): __lowercase : str = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) __lowercase : Any = res[1].strip() if sec_titles == "": __lowercase : List[str] = '[{}]({})'.format(res[0], wiki_url) else: __lowercase : Union[str, Any] = sec_titles.split(' & ') __lowercase : str = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: __lowercase : str = find_nearest_training(question) __lowercase : Optional[int] = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) __lowercase : Any = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) __lowercase : List[Any] = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
27
0
'''simple docstring''' import random def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] ) ->Optional[int]: _SCREAMING_SNAKE_CASE = a[left_index] _SCREAMING_SNAKE_CASE = left_index + 1 for j in range(left_index + 1 , __lowerCamelCase ): if a[j] < pivot: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = a[i], a[j] i += 1 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = a[i - 1], a[left_index] return i - 1 def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int ) ->str: if left < right: _SCREAMING_SNAKE_CASE = random.randint(__lowerCamelCase , right - 1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = ( a[left], a[pivot], ) # switches the pivot with the left most bound _SCREAMING_SNAKE_CASE = partition(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) quick_sort_random( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # recursive quicksort to the left of the pivot point quick_sort_random( __lowerCamelCase , pivot_index + 1 , __lowerCamelCase ) # recursive quicksort to the right of the pivot point def lowerCamelCase ( ) ->Tuple: _SCREAMING_SNAKE_CASE = input("""Enter numbers separated by a comma:\n""" ).strip() _SCREAMING_SNAKE_CASE = [int(__lowerCamelCase ) for item in user_input.split(""",""" )] quick_sort_random(__lowerCamelCase , 0 , len(__lowerCamelCase ) ) print(__lowerCamelCase ) if __name__ == "__main__": main()
58
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __lowercase : Tuple = logging.get_logger(__name__) __lowercase : List[Any] = torch.device('cpu') def lowerCamelCase (): __a : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __a : Tuple = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0, 8.8_6_8_5e-0_1, 2.4_3_6_0e-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6e-0_1, 2.3_4_7_8e-0_1, -1.6_9_6_3e0_0, -1.7_3_8_1e0_0, -8.6_3_3_7e-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8e-0_1, -4.7_4_2_9e-0_1, -1.0_8_9_7e0_0, -1.0_2_4_8e0_0, 3.5_5_2_3e-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0e-0_1, 2.4_2_1_1e-0_1, -6.0_1_8_5e-0_1, -8.2_7_8_9e-0_1, -6.0_4_4_6e-0_2] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : int = dct.pop(_SCREAMING_SNAKE_CASE ) __a : Tuple = val def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : Dict = [] for k in state_dict.keys(): __a : List[Any] = k if ".pwconv" in k: __a : List[Any] = k_new.replace('.pwconv' , '.point_wise_conv' ) if ".dwconv" in k: __a : Dict = k_new.replace('.dwconv' , '.depth_wise_conv' ) if ".Proj." in k: __a : Optional[int] = k_new.replace('.Proj.' , '.proj.' ) if "patch_embed" in k_new: __a : List[Any] = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' ) if "network" in k_new: __a : Union[str, Any] = k_new.split('.' ) if ls[2].isdigit(): __a : Union[str, Any] = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] ) else: __a : Union[str, Any] = k_new.replace('network' , 'swiftformer.encoder.network' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Union[str, Any] = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size __a : List[str] = 1_000 __a : Tuple = 'huggingface/label-files' __a : str = 'imagenet-1k-id2label.json' __a : Dict = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) __a : Optional[int] = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a : Any = idalabel __a : str = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": __a : Dict = [3, 3, 6, 4] __a : int = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": __a : Dict = [3, 3, 9, 6] __a : List[str] = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": __a : Dict = [4, 3, 10, 5] __a : Optional[int] = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": __a : Tuple = [4, 4, 12, 6] __a : Dict = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('https' ): __a : List[Any] = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE ) else: __a : Union[str, Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) __a : Optional[Any] = checkpoint __a : Dict = create_rename_keys(_SCREAMING_SNAKE_CASE ) for rename_key_src, rename_key_dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model __a : Tuple = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval() hf_model.load_state_dict(_SCREAMING_SNAKE_CASE ) # prepare test inputs __a : Tuple = prepare_img() __a : str = ViTImageProcessor.from_pretrained('preprocessor_config' ) __a : Tuple = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # compare outputs from both models __a : List[Any] = get_expected_output(_SCREAMING_SNAKE_CASE ) __a : Dict = hf_model(inputs['pixel_values'] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swiftformer_name', default='swiftformer_xs', choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'], type=str, help='Name of the SwiftFormer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='./converted_outputs/', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.') __lowercase : Tuple = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
27
0
import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __lowerCamelCase = logging.get_logger(__name__) class UpperCAmelCase ( A_ ): A__ : List[Any] = ["input_features"] def __init__(self : List[str] , snake_case__ : int=80 , snake_case__ : List[Any]=1_60_00 , snake_case__ : List[Any]=1_60 , snake_case__ : Tuple=30 , snake_case__ : Dict=4_00 , snake_case__ : str=0.0 , snake_case__ : Optional[int]=False , **snake_case__ : Dict , ) -> List[str]: '''simple docstring''' super().__init__( feature_size=snake_case__ , sampling_rate=snake_case__ , padding_value=snake_case__ , return_attention_mask=snake_case__ , **snake_case__ , ) snake_case : Dict = n_fft snake_case : List[Any] = hop_length snake_case : List[Any] = chunk_length snake_case : List[str] = chunk_length * sampling_rate snake_case : int = self.n_samples // hop_length snake_case : List[Any] = sampling_rate snake_case : List[str] = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=snake_case__ , min_frequency=0.0 , max_frequency=8000.0 , sampling_rate=snake_case__ , norm="slaney" , mel_scale="slaney" , ) def _SCREAMING_SNAKE_CASE (self : Union[str, Any] , snake_case__ : np.array ) -> np.ndarray: '''simple docstring''' snake_case : Any = spectrogram( snake_case__ , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="log10" , ) snake_case : str = log_spec[:, :-1] snake_case : Any = np.maximum(snake_case__ , log_spec.max() - 8.0 ) snake_case : List[str] = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def _SCREAMING_SNAKE_CASE (snake_case__ : List[np.ndarray] , snake_case__ : List[np.ndarray] , snake_case__ : float = 0.0 ) -> List[np.ndarray]: '''simple docstring''' if attention_mask is not None: snake_case : Any = np.array(snake_case__ , np.intaa ) snake_case : Dict = [] for vector, length in zip(snake_case__ , attention_mask.sum(-1 ) ): snake_case : Dict = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: snake_case : Union[str, Any] = padding_value normed_input_values.append(snake_case__ ) else: snake_case : List[str] = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def __call__(self : str , snake_case__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , snake_case__ : bool = True , snake_case__ : Optional[int] = None , snake_case__ : Optional[Union[str, TensorType]] = None , snake_case__ : Optional[bool] = None , snake_case__ : Optional[str] = "max_length" , snake_case__ : Optional[int] = None , snake_case__ : Optional[int] = None , snake_case__ : Optional[bool] = None , **snake_case__ : List[Any] , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) snake_case : Optional[int] = isinstance(snake_case__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) snake_case : List[Any] = is_batched_numpy or ( isinstance(snake_case__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: snake_case : str = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(snake_case__ , np.ndarray ): snake_case : List[str] = np.asarray(snake_case__ , dtype=np.floataa ) elif isinstance(snake_case__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): snake_case : List[str] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: snake_case : Dict = [np.asarray([raw_speech] ).T] snake_case : Optional[int] = BatchFeature({"input_features": raw_speech} ) # convert into correct format for padding snake_case : Optional[Any] = self.pad( snake_case__ , padding=snake_case__ , max_length=max_length if max_length else self.n_samples , truncation=snake_case__ , pad_to_multiple_of=snake_case__ , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: snake_case : Optional[Any] = self.zero_mean_unit_var_norm( padded_inputs["input_features"] , attention_mask=padded_inputs["attention_mask"] , padding_value=self.padding_value , ) snake_case : Union[str, Any] = np.stack(padded_inputs["input_features"] , axis=0 ) # make sure list is in array format snake_case : List[Any] = padded_inputs.get("input_features" ).transpose(2 , 0 , 1 ) snake_case : str = [self._np_extract_fbank_features(snake_case__ ) for waveform in input_features[0]] if isinstance(input_features[0] , snake_case__ ): snake_case : Dict = [np.asarray(snake_case__ , dtype=np.floataa ) for feature in input_features] else: snake_case : Tuple = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) snake_case : str = padded_inputs["attention_mask"][:, :: self.hop_length] if return_tensors is not None: snake_case : int = padded_inputs.convert_to_tensors(snake_case__ ) return padded_inputs def _SCREAMING_SNAKE_CASE (self : Union[str, Any] ) -> Dict[str, Any]: '''simple docstring''' snake_case : Union[str, Any] = copy.deepcopy(self.__dict__ ) snake_case : Dict = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
59
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __lowercase : Dict = logging.get_logger(__name__) __lowercase : Optional[Any] = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "umt5" A_ = ["past_key_values"] def __init__( self , __a=25_0112 , __a=512 , __a=64 , __a=1024 , __a=8 , __a=None , __a=6 , __a=32 , __a=128 , __a=0.1 , __a=1E-6 , __a=1.0 , __a="gated-gelu" , __a=True , __a=True , __a="T5Tokenizer" , __a=True , __a=0 , __a=1 , __a=0 , **__a , ): '''simple docstring''' super().__init__( is_encoder_decoder=__a , tokenizer_class=__a , tie_word_embeddings=__a , pad_token_id=__a , eos_token_id=__a , decoder_start_token_id=__a , **__a , ) __a : Any = vocab_size __a : Any = d_model __a : str = d_kv __a : Dict = d_ff __a : Union[str, Any] = num_layers __a : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __a : Optional[int] = num_heads __a : Tuple = relative_attention_num_buckets __a : Optional[Any] = relative_attention_max_distance __a : Optional[int] = dropout_rate __a : List[Any] = layer_norm_epsilon __a : int = initializer_factor __a : Union[str, Any] = feed_forward_proj __a : Any = use_cache __a : List[Any] = self.feed_forward_proj.split('-' ) __a : Dict = act_info[-1] __a : Dict = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) if feed_forward_proj == "gated-gelu": __a : Optional[int] = 'gelu_new' @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.d_model @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_heads @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_layers class __UpperCamelCase ( lowerCAmelCase_ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __a : Dict = 'past_encoder_sequence + sequence' __a : Tuple = {0: 'batch'} __a : Tuple = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __a : List[Any] = {0: 'batch', 1: 'decoder_sequence'} __a : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __UpperCAmelCase ( self ): '''simple docstring''' return 13 @property def __UpperCAmelCase ( self ): '''simple docstring''' return 5E-4
27
0
"""simple docstring""" from __future__ import annotations import math def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : bool , _snake_case : list[int] , _snake_case : float ): if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if not scores: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , _snake_case , _snake_case , _snake_case ) , minimax(depth + 1 , node_index * 2 + 1 , _snake_case , _snake_case , _snake_case ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , _snake_case , _snake_case , _snake_case ) , minimax(depth + 1 , node_index * 2 + 1 , _snake_case , _snake_case , _snake_case ) , ) ) def _snake_case ( ): lowerCAmelCase : Optional[int] = [90, 23, 6, 33, 21, 65, 123, 34423] lowerCAmelCase : Union[str, Any] = math.log(len(_snake_case ) , 2 ) print(f'''Optimal value : {minimax(0 , 0 , _snake_case , _snake_case , _snake_case )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
60
'''simple docstring''' import requests from bsa import BeautifulSoup def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "https://www.worldometers.info/coronavirus" ): __a : List[Any] = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE ).text , 'html.parser' ) __a : Union[str, Any] = soup.findAll('h1' ) __a : int = soup.findAll('div' , {'class': 'maincounter-number'} ) keys += soup.findAll('span' , {'class': 'panel-title'} ) values += soup.findAll('div' , {'class': 'number-table-main'} ) return {key.text.strip(): value.text.strip() for key, value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
27
0
"""simple docstring""" import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = ComputeEnvironment.AMAZON_SAGEMAKER SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Tuple = """ml.p3.2xlarge""" SCREAMING_SNAKE_CASE__ : Dict = """accelerate_sagemaker_execution_role""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = """hf-sm""" SCREAMING_SNAKE_CASE__ : str = """us-east-1""" SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Any = """accelerate-sagemaker-1""" SCREAMING_SNAKE_CASE__ : List[str] = """1.6""" SCREAMING_SNAKE_CASE__ : Tuple = """4.4""" SCREAMING_SNAKE_CASE__ : List[str] = """train.py""" SCREAMING_SNAKE_CASE__ : Any = [ """--model_name_or_path""", """bert""", """--do_train""", """False""", """--epochs""", """3""", """--learning_rate""", """5e-5""", """--max_steps""", """50.5""", ] SCREAMING_SNAKE_CASE__ : Optional[Any] = [ """--model_name_or_path""", """bert""", """--do_train""", """--do_test""", """False""", """--do_predict""", """--epochs""", """3""", """--learning_rate""", """5e-5""", """--max_steps""", """50.5""", ] class A_ (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self ): """simple docstring""" # If no defaults are changed, `to_kwargs` returns an empty dict. UpperCAmelCase_ : Dict = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args ) assert isinstance(converted_args["model_name_or_path"] , lowercase_ ) assert isinstance(converted_args["do_train"] , lowercase_ ) assert isinstance(converted_args["epochs"] , lowercase_ ) assert isinstance(converted_args["learning_rate"] , lowercase_ ) assert isinstance(converted_args["max_steps"] , lowercase_ ) with pytest.raises(lowercase_ ): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args )
61
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__a , 'embed_dim' ) ) self.parent.assertTrue(hasattr(__a , 'num_heads' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=64 , __a=3 , __a=[16, 48, 96] , __a=[1, 3, 6] , __a=[1, 2, 10] , __a=[7, 3, 3] , __a=[4, 2, 2] , __a=[2, 1, 1] , __a=[2, 2, 2] , __a=[False, False, True] , __a=[0.0, 0.0, 0.0] , __a=0.02 , __a=1E-1_2 , __a=True , __a=True , __a=2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : Optional[int] = image_size __a : List[str] = patch_sizes __a : str = patch_stride __a : Any = patch_padding __a : Dict = is_training __a : Union[str, Any] = use_labels __a : Dict = num_labels __a : List[Any] = num_channels __a : Any = embed_dim __a : int = num_heads __a : Optional[int] = stride_kv __a : Dict = depth __a : List[str] = cls_token __a : List[Any] = attention_drop_rate __a : Tuple = initializer_range __a : int = layer_norm_eps def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Dict = None if self.use_labels: # create a random int32 tensor of given shape __a : str = ids_tensor([self.batch_size] , self.num_labels ) __a : str = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = TFCvtModel(config=__a ) __a : Dict = model(__a , training=__a ) __a : Any = (self.image_size, self.image_size) __a , __a : Dict = image_size[0], image_size[1] for i in range(len(self.depth ) ): __a : Tuple = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) __a : str = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : List[Any] = self.num_labels __a : Optional[int] = TFCvtForImageClassification(__a ) __a : Dict = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () A_ = ( {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification} if is_tf_available() else {} ) A_ = False A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtModelTester(self ) __a : List[Any] = TFCvtConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason='Cvt does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = tf.keras.mixed_precision.Policy('mixed_float16' ) tf.keras.mixed_precision.set_global_policy(__a ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('float32' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : List[str] = model_class(__a ) __a : Union[str, Any] = model(**self._prepare_for_class(__a , __a ) ) __a : Any = outputs.hidden_states __a : Union[str, Any] = len(self.model_tester.depth ) self.assertEqual(len(__a ) , __a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[str] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[Any] = TFCvtModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __a : Tuple = self.default_image_processor __a : Any = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ) # forward pass __a : Any = model(**__a ) # verify the logits __a : Any = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __a : Optional[Any] = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __a , atol=1E-4 ) )
27
0
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) _A = logging.get_logger(__name__) _A = OrderedDict( [ ('align', 'EfficientNetImageProcessor'), ('beit', 'BeitImageProcessor'), ('bit', 'BitImageProcessor'), ('blip', 'BlipImageProcessor'), ('blip-2', 'BlipImageProcessor'), ('bridgetower', 'BridgeTowerImageProcessor'), ('chinese_clip', 'ChineseCLIPImageProcessor'), ('clip', 'CLIPImageProcessor'), ('clipseg', 'ViTImageProcessor'), ('conditional_detr', 'ConditionalDetrImageProcessor'), ('convnext', 'ConvNextImageProcessor'), ('convnextv2', 'ConvNextImageProcessor'), ('cvt', 'ConvNextImageProcessor'), ('data2vec-vision', 'BeitImageProcessor'), ('deformable_detr', 'DeformableDetrImageProcessor'), ('deit', 'DeiTImageProcessor'), ('deta', 'DetaImageProcessor'), ('detr', 'DetrImageProcessor'), ('dinat', 'ViTImageProcessor'), ('donut-swin', 'DonutImageProcessor'), ('dpt', 'DPTImageProcessor'), ('efficientformer', 'EfficientFormerImageProcessor'), ('efficientnet', 'EfficientNetImageProcessor'), ('flava', 'FlavaImageProcessor'), ('focalnet', 'BitImageProcessor'), ('git', 'CLIPImageProcessor'), ('glpn', 'GLPNImageProcessor'), ('groupvit', 'CLIPImageProcessor'), ('imagegpt', 'ImageGPTImageProcessor'), ('instructblip', 'BlipImageProcessor'), ('layoutlmv2', 'LayoutLMv2ImageProcessor'), ('layoutlmv3', 'LayoutLMv3ImageProcessor'), ('levit', 'LevitImageProcessor'), ('mask2former', 'Mask2FormerImageProcessor'), ('maskformer', 'MaskFormerImageProcessor'), ('mgp-str', 'ViTImageProcessor'), ('mobilenet_v1', 'MobileNetV1ImageProcessor'), ('mobilenet_v2', 'MobileNetV2ImageProcessor'), ('mobilevit', 'MobileViTImageProcessor'), ('mobilevit', 'MobileViTImageProcessor'), ('mobilevitv2', 'MobileViTImageProcessor'), ('nat', 'ViTImageProcessor'), ('oneformer', 'OneFormerImageProcessor'), ('owlvit', 'OwlViTImageProcessor'), ('perceiver', 'PerceiverImageProcessor'), ('pix2struct', 'Pix2StructImageProcessor'), ('poolformer', 'PoolFormerImageProcessor'), ('regnet', 'ConvNextImageProcessor'), ('resnet', 'ConvNextImageProcessor'), ('sam', 'SamImageProcessor'), ('segformer', 'SegformerImageProcessor'), ('swiftformer', 'ViTImageProcessor'), ('swin', 'ViTImageProcessor'), ('swin2sr', 'Swin2SRImageProcessor'), ('swinv2', 'ViTImageProcessor'), ('table-transformer', 'DetrImageProcessor'), ('timesformer', 'VideoMAEImageProcessor'), ('tvlt', 'TvltImageProcessor'), ('upernet', 'SegformerImageProcessor'), ('van', 'ConvNextImageProcessor'), ('videomae', 'VideoMAEImageProcessor'), ('vilt', 'ViltImageProcessor'), ('vit', 'ViTImageProcessor'), ('vit_hybrid', 'ViTHybridImageProcessor'), ('vit_mae', 'ViTImageProcessor'), ('vit_msn', 'ViTImageProcessor'), ('xclip', 'CLIPImageProcessor'), ('yolos', 'YolosImageProcessor'), ] ) _A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: __UpperCamelCase =model_type_to_module_name(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =importlib.import_module(F'.{module_name}' , 'transformers.models' ) try: return getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(SCREAMING_SNAKE_CASE__ , '__name__' , SCREAMING_SNAKE_CASE__ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. __UpperCamelCase =importlib.import_module('transformers' ) if hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return None def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, os.PathLike]] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, str]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[bool, str]] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : bool = False , **SCREAMING_SNAKE_CASE__ : Dict , ): __UpperCamelCase =get_file_from_repo( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ , resume_download=SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , use_auth_token=SCREAMING_SNAKE_CASE__ , revision=SCREAMING_SNAKE_CASE__ , local_files_only=SCREAMING_SNAKE_CASE__ , ) if resolved_config_file is None: logger.info( 'Could not locate the image processor configuration file, will try to use the model config instead.' ) return {} with open(SCREAMING_SNAKE_CASE__ , encoding='utf-8' ) as reader: return json.load(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self ) -> Any: raise EnvironmentError( 'AutoImageProcessor is designed to be instantiated ' 'using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(A_ ) def _a ( cls , A_ , **A_ ) -> Union[str, Any]: __UpperCamelCase =kwargs.pop('config' , A_ ) __UpperCamelCase =kwargs.pop('trust_remote_code' , A_ ) __UpperCamelCase =True __UpperCamelCase , __UpperCamelCase =ImageProcessingMixin.get_image_processor_dict(A_ , **A_ ) __UpperCamelCase =config_dict.get('image_processor_type' , A_ ) __UpperCamelCase =None if "AutoImageProcessor" in config_dict.get('auto_map' , {} ): __UpperCamelCase =config_dict['auto_map']['AutoImageProcessor'] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: __UpperCamelCase =config_dict.pop('feature_extractor_type' , A_ ) if feature_extractor_class is not None: logger.warning( 'Could not find image processor class in the image processor config or the model config. Loading' ' based on pattern matching with the model\'s feature extractor configuration.' ) __UpperCamelCase =feature_extractor_class.replace('FeatureExtractor' , 'ImageProcessor' ) if "AutoFeatureExtractor" in config_dict.get('auto_map' , {} ): __UpperCamelCase =config_dict['auto_map']['AutoFeatureExtractor'] __UpperCamelCase =feature_extractor_auto_map.replace('FeatureExtractor' , 'ImageProcessor' ) logger.warning( 'Could not find image processor auto map in the image processor config or the model config.' ' Loading based on pattern matching with the model\'s feature extractor configuration.' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(A_ , A_ ): __UpperCamelCase =AutoConfig.from_pretrained(A_ , **A_ ) # It could be in `config.image_processor_type`` __UpperCamelCase =getattr(A_ , 'image_processor_type' , A_ ) if hasattr(A_ , 'auto_map' ) and "AutoImageProcessor" in config.auto_map: __UpperCamelCase =config.auto_map['AutoImageProcessor'] if image_processor_class is not None: __UpperCamelCase =image_processor_class_from_name(A_ ) __UpperCamelCase =image_processor_auto_map is not None __UpperCamelCase =image_processor_class is not None or type(A_ ) in IMAGE_PROCESSOR_MAPPING __UpperCamelCase =resolve_trust_remote_code( A_ , A_ , A_ , A_ ) if has_remote_code and trust_remote_code: __UpperCamelCase =get_class_from_dynamic_module( A_ , A_ , **A_ ) __UpperCamelCase =kwargs.pop('code_revision' , A_ ) if os.path.isdir(A_ ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(A_ , **A_ ) elif image_processor_class is not None: return image_processor_class.from_dict(A_ , **A_ ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(A_ ) in IMAGE_PROCESSOR_MAPPING: __UpperCamelCase =IMAGE_PROCESSOR_MAPPING[type(A_ )] return image_processor_class.from_dict(A_ , **A_ ) raise ValueError( f'Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ' f'`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ' f'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}' ) @staticmethod def _a ( A_ , A_ ) -> List[str]: IMAGE_PROCESSOR_MAPPING.register(A_ , A_ )
62
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __lowercase : Union[str, Any] = logging.get_logger(__name__) __lowercase : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } __lowercase : Optional[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): for attribute in key.split('.' ): __a : Any = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: __a : Any = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __a : Tuple = value elif weight_type == "weight_g": __a : str = value elif weight_type == "weight_v": __a : Optional[Any] = value elif weight_type == "bias": __a : Union[str, Any] = value else: __a : List[Any] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : int = [] __a : List[str] = fairseq_model.state_dict() __a : Tuple = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight __a : int = None for name, value in fairseq_dict.items(): __a : List[str] = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == 'group' , ) __a : List[str] = True elif name.split('.' )[0] == "proj": __a : Tuple = fairseq_model.proj __a : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __a : List[Any] = True if "*" in mapped_key: __a : str = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2] __a : int = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: __a : List[Any] = 'weight_g' elif "weight_v" in name: __a : List[Any] = 'weight_v' elif "bias" in name: __a : Optional[Any] = 'bias' elif "weight" in name: __a : Tuple = 'weight' else: __a : Optional[Any] = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : List[str] = full_name.split('conv_layers.' )[-1] __a : Any = name.split('.' ) __a : List[str] = int(items[0] ) __a : List[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __a : List[str] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __a : str = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) __a : Tuple = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __a : List[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a , __a : List[str] = emb.weight.shape __a : str = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) __a : Optional[int] = emb.weight.data return lin_layer def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any ): with open(_SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' ) as f: __a : Union[str, Any] = f.readlines() __a : Tuple = [line.split(' ' )[0] for line in lines] __a : int = len(_SCREAMING_SNAKE_CASE ) __a : List[Any] = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(_SCREAMING_SNAKE_CASE , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int] , ): __a : Optional[int] = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : Any = SpeechaTextaConfig.from_pretrained( _SCREAMING_SNAKE_CASE , vocab_size=_SCREAMING_SNAKE_CASE , decoder_layers=_SCREAMING_SNAKE_CASE , do_stable_layer_norm=_SCREAMING_SNAKE_CASE ) __a : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) __a , __a , __a : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) __a : Optional[int] = model[0].eval() # set weights for wav2vec2 encoder __a : Tuple = WavaVecaModel(_SCREAMING_SNAKE_CASE ) __a : int = recursively_load_weights_wavaveca(model.encoder , _SCREAMING_SNAKE_CASE ) __a : Dict = SpeechaTextaForCausalLM(_SCREAMING_SNAKE_CASE ) __a , __a : Optional[int] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_SCREAMING_SNAKE_CASE ) # set output linear layer unexpected_keys.remove('embed_out' ) __a : Optional[Any] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) __a : Tuple = SpeechEncoderDecoderModel(encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) __a : int = False # add projection layer __a : str = nn.Parameter(projection_layer.weight ) __a : Any = nn.Parameter(projection_layer.bias ) __a : str = create_vocab_dict(_SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) , 'w' ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = SpeechaTextaTokenizer(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) ) tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = hf_wavavec.config.to_dict() __a : Tuple = tokenizer.pad_token_id __a : Optional[int] = tokenizer.bos_token_id __a : Union[str, Any] = tokenizer.eos_token_id __a : Tuple = 'speech_to_text_2' __a : Tuple = 'wav2vec2' __a : List[str] = SpeechEncoderDecoderConfig.from_dict(_SCREAMING_SNAKE_CASE ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-large-lv60', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/s2t-small-mustc-en-fr-st', type=str, help='Path to hf decoder s2t checkpoint config', ) parser.add_argument('--vocab_size', default=1_02_24, type=int, help='Vocab size of decoder') parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers') __lowercase : Tuple = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
27
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCAmelCase_ : Any = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : int = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Optional[Any] = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys lowerCAmelCase_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
63
'''simple docstring''' # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int ): with open(_SCREAMING_SNAKE_CASE , 'r' ) as fh: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_EX ) try: print(*_SCREAMING_SNAKE_CASE ) finally: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) __lowercase : Dict = int(os.environ['LOCAL_RANK']) torch.cuda.set_device(local_rank) __lowercase : Tuple = torch.device('cuda', local_rank) __lowercase : Optional[int] = socket.gethostname() __lowercase : List[str] = f'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group('nccl') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __lowercase : str = dist.get_rank() __lowercase : Union[str, Any] = dist.get_world_size() printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(f'''{gpu} is broken''') raise
27
0
"""simple docstring""" import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version A_ = logging.getLogger(__name__) require_version('''pytorch_lightning>=1.0.4''') A_ = { '''base''': AutoModel, '''sequence-classification''': AutoModelForSequenceClassification, '''question-answering''': AutoModelForQuestionAnswering, '''pretraining''': AutoModelForPreTraining, '''token-classification''': AutoModelForTokenClassification, '''language-modeling''': AutoModelWithLMHead, '''summarization''': AutoModelForSeqaSeqLM, '''translation''': AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization A_ = { '''linear''': get_linear_schedule_with_warmup, '''cosine''': get_cosine_schedule_with_warmup, '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup, '''polynomial''': get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } A_ = sorted(arg_to_scheduler.keys()) A_ = '''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}''' class lowercase( pl.LightningModule ): '''simple docstring''' def __init__( self: List[str], a_: argparse.Namespace, a_: Tuple=None, a_: Dict="base", a_: Tuple=None, a_: Union[str, Any]=None, a_: int=None, **a_: int, ): '''simple docstring''' super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(a_ ) _snake_case : Any = 0 _snake_case : str = Path(self.hparams.output_dir ) _snake_case : List[Any] = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: _snake_case : Optional[int] = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path, **({"""num_labels""": num_labels} if num_labels is not None else {}), cache_dir=a_, **a_, ) else: _snake_case : PretrainedConfig = config _snake_case : Dict = ("""encoder_layerdrop""", """decoder_layerdrop""", """dropout""", """attention_dropout""") for p in extra_model_params: if getattr(self.hparams, a_, a_ ): assert hasattr(self.config, a_ ), f"model config doesn't have a `{p}` attribute" setattr(self.config, a_, getattr(self.hparams, a_ ) ) if tokenizer is None: _snake_case : Union[str, Any] = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path, cache_dir=a_, ) else: _snake_case : PreTrainedTokenizer = tokenizer _snake_case : Union[str, Any] = MODEL_MODES[mode] if model is None: _snake_case : Dict = self.model_type.from_pretrained( self.hparams.model_name_or_path, from_tf=bool(""".ckpt""" in self.hparams.model_name_or_path ), config=self.config, cache_dir=a_, ) else: _snake_case : int = model def UpperCamelCase_ ( self: Dict, *a_: Dict, **a_: List[str] ): '''simple docstring''' _snake_case : List[Any] = self.model_type.from_pretrained(*a_, **a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Dict = arg_to_scheduler[self.hparams.lr_scheduler] _snake_case : Optional[int] = get_schedule_func( self.opt, num_warmup_steps=self.hparams.warmup_steps, num_training_steps=self.total_steps() ) _snake_case : Dict = {"""scheduler""": scheduler, """interval""": """step""", """frequency""": 1} return scheduler def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Any = self.model _snake_case : List[Any] = ["""bias""", """LayerNorm.weight"""] _snake_case : Any = [ { """params""": [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters """weight_decay""": self.hparams.weight_decay, }, { """params""": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], """weight_decay""": 0.0, }, ] if self.hparams.adafactor: _snake_case : Optional[int] = Adafactor( a_, lr=self.hparams.learning_rate, scale_parameter=a_, relative_step=a_ ) else: _snake_case : Optional[int] = AdamW( a_, lr=self.hparams.learning_rate, eps=self.hparams.adam_epsilon ) _snake_case : Optional[Any] = optimizer _snake_case : Tuple = self.get_lr_scheduler() return [optimizer], [scheduler] def UpperCamelCase_ ( self: int, a_: int, a_: Optional[Any] ): '''simple docstring''' return self.validation_step(a_, a_ ) def UpperCamelCase_ ( self: Optional[Any], a_: Union[str, Any] ): '''simple docstring''' return self.validation_end(a_ ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : List[Any] = max(1, self.hparams.gpus ) # TODO: consider num_tpu_cores _snake_case : Optional[Any] = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def UpperCamelCase_ ( self: Optional[Any], a_: Optional[Any] ): '''simple docstring''' if stage == "test": _snake_case : Union[str, Any] = len(self.test_dataloader().dataset ) else: _snake_case : Union[str, Any] = self.get_dataloader("""train""", self.hparams.train_batch_size, shuffle=a_ ) _snake_case : Union[str, Any] = len(self.train_dataloader().dataset ) def UpperCamelCase_ ( self: List[Any], a_: str, a_: int, a_: bool = False ): '''simple docstring''' raise NotImplementedError("""You must implement this for your task""" ) def UpperCamelCase_ ( self: str ): '''simple docstring''' return self.train_loader def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' return self.get_dataloader("""dev""", self.hparams.eval_batch_size, shuffle=a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' return self.get_dataloader("""test""", self.hparams.eval_batch_size, shuffle=a_ ) def UpperCamelCase_ ( self: Dict, a_: int ): '''simple docstring''' return os.path.join( self.hparams.data_dir, """cached_{}_{}_{}""".format( a_, list(filter(a_, self.hparams.model_name_or_path.split("""/""" ) ) ).pop(), str(self.hparams.max_seq_length ), ), ) @pl.utilities.rank_zero_only def UpperCamelCase_ ( self: str, a_: Dict[str, Any] ): '''simple docstring''' _snake_case : Optional[int] = self.output_dir.joinpath("""best_tfmr""" ) _snake_case : Optional[int] = self.step_count self.model.save_pretrained(a_ ) self.tokenizer.save_pretrained(a_ ) @staticmethod def UpperCamelCase_ ( a_: Dict, a_: Dict ): '''simple docstring''' parser.add_argument( """--model_name_or_path""", default=a_, type=a_, required=a_, help="""Path to pretrained model or model identifier from huggingface.co/models""", ) parser.add_argument( """--config_name""", default="""""", type=a_, help="""Pretrained config name or path if not the same as model_name""" ) parser.add_argument( """--tokenizer_name""", default=a_, type=a_, help="""Pretrained tokenizer name or path if not the same as model_name""", ) parser.add_argument( """--cache_dir""", default=str(Path(a_ ).parent / """test_run""" / """cache""" ), type=a_, help="""Where do you want to store the pre-trained models downloaded from huggingface.co""", ) parser.add_argument( """--encoder_layerdrop""", type=a_, help="""Encoder layer dropout probability (Optional). Goes into model.config""", ) parser.add_argument( """--decoder_layerdrop""", type=a_, help="""Decoder layer dropout probability (Optional). Goes into model.config""", ) parser.add_argument( """--dropout""", type=a_, help="""Dropout probability (Optional). Goes into model.config""", ) parser.add_argument( """--attention_dropout""", type=a_, help="""Attention dropout probability (Optional). Goes into model.config""", ) parser.add_argument("""--learning_rate""", default=5E-5, type=a_, help="""The initial learning rate for Adam.""" ) parser.add_argument( """--lr_scheduler""", default="""linear""", choices=a_, metavar=a_, type=a_, help="""Learning rate scheduler""", ) parser.add_argument("""--weight_decay""", default=0.0, type=a_, help="""Weight decay if we apply some.""" ) parser.add_argument("""--adam_epsilon""", default=1E-8, type=a_, help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--warmup_steps""", default=0, type=a_, help="""Linear warmup over warmup_steps.""" ) parser.add_argument("""--num_workers""", default=4, type=a_, help="""kwarg passed to DataLoader""" ) parser.add_argument("""--num_train_epochs""", dest="""max_epochs""", default=3, type=a_ ) parser.add_argument("""--train_batch_size""", default=32, type=a_ ) parser.add_argument("""--eval_batch_size""", default=32, type=a_ ) parser.add_argument("""--adafactor""", action="""store_true""" ) class lowercase( pl.Callback ): '''simple docstring''' def UpperCamelCase_ ( self: Optional[int], a_: Optional[int], a_: Any ): '''simple docstring''' if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class lowercase( pl.Callback ): '''simple docstring''' def UpperCamelCase_ ( self: str, a_: Optional[Any], a_: List[str] ): '''simple docstring''' for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(a_ ) class lowercase( pl.Callback ): '''simple docstring''' def UpperCamelCase_ ( self: List[Any], a_: Union[str, Any], a_: str ): '''simple docstring''' _snake_case : Any = trainer.lr_schedulers[0]["""scheduler"""] _snake_case : List[str] = {f"lr_group_{i}": lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(a_ ) def UpperCamelCase_ ( self: Dict, a_: pl.Trainer, a_: pl.LightningModule ): '''simple docstring''' rank_zero_info("""***** Validation results *****""" ) _snake_case : List[str] = trainer.callback_metrics # Log results for key in sorted(a_ ): if key not in ["log", "progress_bar"]: rank_zero_info("""{} = {}\n""".format(a_, str(metrics[key] ) ) ) def UpperCamelCase_ ( self: Any, a_: pl.Trainer, a_: pl.LightningModule ): '''simple docstring''' rank_zero_info("""***** Test results *****""" ) _snake_case : Union[str, Any] = trainer.callback_metrics # Log and save results to file _snake_case : str = os.path.join(pl_module.hparams.output_dir, """test_results.txt""" ) with open(a_, """w""" ) as writer: for key in sorted(a_ ): if key not in ["log", "progress_bar"]: rank_zero_info("""{} = {}\n""".format(a_, str(metrics[key] ) ) ) writer.write("""{} = {}\n""".format(a_, str(metrics[key] ) ) ) def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : Optional[int] ): """simple docstring""" parser.add_argument( """--output_dir""" , default=str(Path(snake_case__ ).parent / """test_run""" / """model_checkpoints""" ) , type=snake_case__ , help="""The output directory where the model predictions and checkpoints will be written.""" , ) 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=snake_case__ , default="""O2""" , 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_tpu_cores""" , dest="""tpu_cores""" , type=snake_case__ ) parser.add_argument("""--max_grad_norm""" , dest="""gradient_clip_val""" , default=1.0 , type=snake_case__ , help="""Max gradient norm""" ) parser.add_argument("""--do_train""" , action="""store_true""" , help="""Whether to run training.""" ) parser.add_argument("""--do_predict""" , action="""store_true""" , help="""Whether to run predictions on the test set.""" ) parser.add_argument( """--gradient_accumulation_steps""" , dest="""accumulate_grad_batches""" , type=snake_case__ , default=1 , help="""Number of updates steps to accumulate before performing a backward/update pass.""" , ) parser.add_argument("""--seed""" , type=snake_case__ , default=42 , help="""random seed for initialization""" ) parser.add_argument( """--data_dir""" , default=str(Path(snake_case__ ).parent / """test_run""" / """dummy-train-data""" ) , type=snake_case__ , help="""The input data dir. Should contain the training files for the CoNLL-2003 NER task.""" , ) def UpperCAmelCase__ (snake_case__ : BaseTransformer , snake_case__ : argparse.Namespace , snake_case__ : int=None , snake_case__ : str=True , snake_case__ : Optional[Any]=[] , snake_case__ : List[str]=None , snake_case__ : Any=None , **snake_case__ : Tuple , ): """simple docstring""" pl.seed_everything(args.seed ) # init model _snake_case : str = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=snake_case__ ) # add custom checkpoints if checkpoint_callback is None: _snake_case : Optional[Any] = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix="""checkpoint""" , monitor="""val_loss""" , mode="""min""" , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(snake_case__ ) if logging_callback is None: _snake_case : Union[str, Any] = LoggingCallback() _snake_case : List[str] = {} if args.fpaa: _snake_case : Union[str, Any] = 16 if args.gpus > 1: _snake_case : Optional[Any] = """auto""" _snake_case : Union[str, Any] = """ddp""" _snake_case : List[str] = args.accumulate_grad_batches _snake_case : Dict = None _snake_case : str = """auto""" _snake_case : Dict = pl.Trainer.from_argparse_args( snake_case__ , weights_summary=snake_case__ , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=snake_case__ , val_check_interval=1 , num_sanity_val_steps=2 , **snake_case__ , ) if args.do_train: trainer.fit(snake_case__ ) else: print("""RAG modeling tests with new set functions successfuly executed!""" ) return trainer
64
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase : str = { '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: __lowercase : str = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] __lowercase : Tuple = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] __lowercase : Dict = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): __lowercase : Optional[Any] = [ '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 __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/config.json'} class A ( UpperCAmelCase_ ): __UpperCAmelCase : List[str] = 'openai-gpt' __UpperCAmelCase : Optional[Any] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__(self : Optional[Any] , __UpperCAmelCase : str=4_0_4_7_8 , __UpperCAmelCase : int=5_1_2 , __UpperCAmelCase : int=7_6_8 , __UpperCAmelCase : Optional[int]=1_2 , __UpperCAmelCase : List[Any]=1_2 , __UpperCAmelCase : Any="gelu" , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : List[str]=1E-5 , __UpperCAmelCase : Dict=0.02 , __UpperCAmelCase : Union[str, Any]="cls_index" , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Any=True , __UpperCAmelCase : List[Any]=0.1 , **__UpperCAmelCase : int , ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = vocab_size UpperCAmelCase__ = n_positions UpperCAmelCase__ = n_embd UpperCAmelCase__ = n_layer UpperCAmelCase__ = n_head UpperCAmelCase__ = afn UpperCAmelCase__ = resid_pdrop UpperCAmelCase__ = embd_pdrop UpperCAmelCase__ = attn_pdrop UpperCAmelCase__ = layer_norm_epsilon UpperCAmelCase__ = initializer_range UpperCAmelCase__ = summary_type UpperCAmelCase__ = summary_use_proj UpperCAmelCase__ = summary_activation UpperCAmelCase__ = summary_first_dropout UpperCAmelCase__ = summary_proj_to_labels super().__init__(**__UpperCAmelCase )
65
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration __lowercase : Tuple = pytest.mark.integration __lowercase : Optional[int] = {'comet'} __lowercase : List[str] = importlib.util.find_spec('fairseq') is not None __lowercase : str = {'code_eval'} __lowercase : List[Any] = os.name == 'nt' __lowercase : Optional[Any] = {'bertscore', 'frugalscore', 'perplexity'} __lowercase : Optional[Any] = importlib.util.find_spec('transformers') is not None def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : int , _SCREAMING_SNAKE_CASE : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (): __a : List[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) @local class __UpperCamelCase ( parameterized.TestCase ): A_ = {} A_ = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = '[...]' __a : Tuple = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) __a : Optional[Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=__a ) # check parameters __a : Dict = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__a , metric_module.__name__ ): with self.use_local_metrics(): try: __a : str = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = '[...]' __a : Optional[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) # run doctest with self.use_local_metrics(): __a : List[Any] = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__a ): yield else: yield @contextmanager def __UpperCAmelCase ( self ): '''simple docstring''' def load_local_metric(__a , *__a , **__a ): return load_metric(os.path.join('metrics' , __a ) , *__a , **__a ) with patch('datasets.load_metric' ) as mock_load_metric: __a : Dict = load_local_metric yield @classmethod def __UpperCAmelCase ( cls , __a ): '''simple docstring''' def wrapper(__a ): __a : Optional[Any] = contextmanager(__a ) __a : str = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self , __a ): '''simple docstring''' assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: __a : Dict = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): import torch def bert_cos_score_idf(_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , *_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Optional[int] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: __a : str = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): def load_from_checkpoint(_SCREAMING_SNAKE_CASE : Optional[int] ): class __UpperCamelCase : def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' assert len(__a ) == 2 __a : Dict = [0.19, 0.92] return scores, sum(__a ) / len(__a ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: __a : str = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: __a : int = load_from_checkpoint yield def lowerCamelCase (): __a : Optional[Any] = load_metric(os.path.join('metrics' , 'seqeval' ) ) __a : List[str] = 'ERROR' __a : List[str] = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): metric.compute(predictions=[] , references=[] , scheme=_SCREAMING_SNAKE_CASE )
27
0
"""simple docstring""" import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def A_ ( _lowercase, _lowercase ): '''simple docstring''' snake_case_ :Optional[int] = torch.load(_lowercase, map_location="""cpu""" ) snake_case_ :Any = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository snake_case_ :Dict = {} for k, v in state_dict.items(): if "pred_layer" in k: snake_case_ :Optional[Any] = v else: snake_case_ :List[str] = v snake_case_ :List[Any] = chkpt["""params"""] snake_case_ :str = {n: v for n, v in config.items() if not isinstance(_lowercase, (torch.FloatTensor, numpy.ndarray) )} snake_case_ :List[Any] = chkpt["""dico_word2id"""] snake_case_ :Optional[Any] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""", """""" ): i for s, i in vocab.items()} # Save pytorch-model snake_case_ :Dict = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME snake_case_ :List[Any] = pytorch_dump_folder_path + """/""" + CONFIG_NAME snake_case_ :Optional[int] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f"""Save PyTorch model to {pytorch_weights_dump_path}""" ) torch.save(_lowercase, _lowercase ) print(f"""Save configuration file to {pytorch_config_dump_path}""" ) with open(_lowercase, """w""", encoding="""utf-8""" ) as f: f.write(json.dumps(_lowercase, indent=2 ) + """\n""" ) print(f"""Save vocab file to {pytorch_config_dump_path}""" ) with open(_lowercase, """w""", encoding="""utf-8""" ) as f: f.write(json.dumps(_lowercase, indent=2 ) + """\n""" ) if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) 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_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
66
'''simple docstring''' import re import string import numpy as np import datasets __lowercase : Tuple = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' __lowercase : List[str] = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' __lowercase : Any = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def __UpperCAmelCase ( 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' ), } ) , reference_urls=[] , ) def __UpperCAmelCase ( self , __a , __a , __a=None , __a=False , __a=False , __a=False , ): '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: __a : Tuple = np.array([re.sub(__a , '' , __a ) for x in predictions] ) __a : List[Any] = np.array([re.sub(__a , '' , __a ) for x in references] ) else: __a : int = np.asarray(__a ) __a : str = np.asarray(__a ) if ignore_case: __a : Dict = np.char.lower(__a ) __a : List[str] = np.char.lower(__a ) if ignore_punctuation: __a : Dict = string.punctuation.maketrans('' , '' , string.punctuation ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Dict = np.char.translate(__a , table=__a ) if ignore_numbers: __a : Optional[int] = string.digits.maketrans('' , '' , string.digits ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Optional[int] = np.char.translate(__a , table=__a ) __a : Any = predictions == references return {"exact_match": np.mean(__a ) * 100}
27
0
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> int: if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): __lowerCamelCase = [image] if isinstance(image[0] , PIL.Image.Image ): __lowerCamelCase = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __lowerCamelCase = np.concatenate(UpperCamelCase__ , axis=0 ) __lowerCamelCase = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 __lowerCamelCase = image.transpose(0 , 3 , 1 , 2 ) __lowerCamelCase = 2.0 * image - 1.0 __lowerCamelCase = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): __lowerCamelCase = torch.cat(UpperCamelCase__ , dim=0 ) return image def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=0.9_9_9_5 ) -> Dict: if not isinstance(UpperCamelCase__ , np.ndarray ): __lowerCamelCase = True __lowerCamelCase = va.device __lowerCamelCase = va.cpu().numpy() __lowerCamelCase = va.cpu().numpy() __lowerCamelCase = np.sum(va * va / (np.linalg.norm(UpperCamelCase__ ) * np.linalg.norm(UpperCamelCase__ )) ) if np.abs(UpperCamelCase__ ) > DOT_THRESHOLD: __lowerCamelCase = (1 - t) * va + t * va else: __lowerCamelCase = np.arccos(UpperCamelCase__ ) __lowerCamelCase = np.sin(UpperCamelCase__ ) __lowerCamelCase = theta_a * t __lowerCamelCase = np.sin(UpperCamelCase__ ) __lowerCamelCase = np.sin(theta_a - theta_t ) / sin_theta_a __lowerCamelCase = sin_theta_t / sin_theta_a __lowerCamelCase = sa * va + sa * va if inputs_are_torch: __lowerCamelCase = torch.from_numpy(UpperCamelCase__ ).to(UpperCamelCase__ ) return va def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: __lowerCamelCase = F.normalize(UpperCamelCase__ , dim=-1 ) __lowerCamelCase = F.normalize(UpperCamelCase__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> str: for param in model.parameters(): __lowerCamelCase = value class a__ ( UpperCAmelCase__ ): def __init__( self : int , a : AutoencoderKL , a : CLIPTextModel , a : CLIPModel , a : CLIPTokenizer , a : UNetaDConditionModel , a : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , a : CLIPFeatureExtractor , a : Any=None , a : str=None , a : int=None , ): """simple docstring""" super().__init__() self.register_modules( vae=a , text_encoder=a , clip_model=a , tokenizer=a , unet=a , scheduler=a , feature_extractor=a , coca_model=a , coca_tokenizer=a , coca_transform=a , ) __lowerCamelCase = ( feature_extractor.size if isinstance(feature_extractor.size , a ) else feature_extractor.size['''shortest_edge'''] ) __lowerCamelCase = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , a ) set_requires_grad(self.clip_model , a ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Optional[Union[str, int]] = "auto" ): """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowerCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" self.enable_attention_slicing(a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" set_requires_grad(self.vae , a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" set_requires_grad(self.vae , a ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" set_requires_grad(self.unet , a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" set_requires_grad(self.unet , a ) def SCREAMING_SNAKE_CASE__ ( self : int , a : Dict , a : List[str] , a : Tuple ): """simple docstring""" __lowerCamelCase = min(int(num_inference_steps * strength ) , a ) __lowerCamelCase = max(num_inference_steps - init_timestep , 0 ) __lowerCamelCase = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE__ ( self : Any , a : int , a : Dict , a : List[str] , a : int , a : str , a : int=None ): """simple docstring""" if not isinstance(a , torch.Tensor ): raise ValueError(f"""`image` has to be of type `torch.Tensor` but is {type(a )}""" ) __lowerCamelCase = image.to(device=a , dtype=a ) if isinstance(a , a ): __lowerCamelCase = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(a ) ] __lowerCamelCase = torch.cat(a , dim=0 ) else: __lowerCamelCase = self.vae.encode(a ).latent_dist.sample(a ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase = 0.1_82_15 * init_latents __lowerCamelCase = init_latents.repeat_interleave(a , dim=0 ) __lowerCamelCase = randn_tensor(init_latents.shape , generator=a , device=a , dtype=a ) # get latents __lowerCamelCase = self.scheduler.add_noise(a , a , a ) __lowerCamelCase = init_latents return latents def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : List[str] ): """simple docstring""" __lowerCamelCase = self.coca_transform(a ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __lowerCamelCase = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __lowerCamelCase = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Union[str, Any] , a : Optional[int] ): """simple docstring""" __lowerCamelCase = self.feature_extractor.preprocess(a ) __lowerCamelCase = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() __lowerCamelCase = self.clip_model.get_image_features(a ) __lowerCamelCase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a ) __lowerCamelCase = image_embeddings_clip.repeat_interleave(a , dim=0 ) return image_embeddings_clip @torch.enable_grad() def SCREAMING_SNAKE_CASE__ ( self : Dict , a : Optional[int] , a : List[Any] , a : Union[str, Any] , a : str , a : Tuple , a : Optional[Any] , a : List[str] , ): """simple docstring""" __lowerCamelCase = latents.detach().requires_grad_() __lowerCamelCase = self.scheduler.scale_model_input(a , a ) # predict the noise residual __lowerCamelCase = self.unet(a , a , encoder_hidden_states=a ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __lowerCamelCase = self.scheduler.alphas_cumprod[timestep] __lowerCamelCase = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowerCamelCase = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __lowerCamelCase = torch.sqrt(a ) __lowerCamelCase = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , a ): __lowerCamelCase = self.scheduler.sigmas[index] __lowerCamelCase = latents - sigma * noise_pred else: raise ValueError(f"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase = 1 / 0.1_82_15 * sample __lowerCamelCase = self.vae.decode(a ).sample __lowerCamelCase = (image / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase = transforms.Resize(self.feature_extractor_size )(a ) __lowerCamelCase = self.normalize(a ).to(latents.dtype ) __lowerCamelCase = self.clip_model.get_image_features(a ) __lowerCamelCase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a ) __lowerCamelCase = spherical_dist_loss(a , a ).mean() * clip_guidance_scale __lowerCamelCase = -torch.autograd.grad(a , a )[0] if isinstance(self.scheduler , a ): __lowerCamelCase = latents.detach() + grads * (sigma**2) __lowerCamelCase = noise_pred_original else: __lowerCamelCase = noise_pred_original - torch.sqrt(a ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Union[str, Any] , a : Union[torch.FloatTensor, PIL.Image.Image] , a : Union[torch.FloatTensor, PIL.Image.Image] , a : Optional[str] = None , a : Optional[str] = None , a : Optional[int] = 5_12 , a : Optional[int] = 5_12 , a : float = 0.6 , a : Optional[int] = 50 , a : Optional[float] = 7.5 , a : Optional[int] = 1 , a : float = 0.0 , a : Optional[float] = 1_00 , a : Optional[torch.Generator] = None , a : Optional[str] = "pil" , a : bool = True , a : float = 0.8 , a : float = 0.1 , a : float = 0.1 , ): """simple docstring""" if isinstance(a , a ) and len(a ) != batch_size: raise ValueError(f"""You have passed {batch_size} batch_size, but only {len(a )} generators.""" ) 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 isinstance(a , torch.Generator ) and batch_size > 1: __lowerCamelCase = [generator] + [None] * (batch_size - 1) __lowerCamelCase = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] __lowerCamelCase = [x[0] for x in coca_is_none if x[1]] __lowerCamelCase = ''', '''.join(a ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(a ): raise ValueError( f"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" f"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) __lowerCamelCase = self.get_image_description(a ) if style_prompt is None: if len(a ): raise ValueError( f"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" f""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) __lowerCamelCase = self.get_image_description(a ) # get prompt text embeddings for content and style __lowerCamelCase = self.tokenizer( a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=a , return_tensors='''pt''' , ) __lowerCamelCase = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __lowerCamelCase = self.tokenizer( a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=a , return_tensors='''pt''' , ) __lowerCamelCase = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __lowerCamelCase = slerp(a , a , a ) # duplicate text embeddings for each generation per prompt __lowerCamelCase = text_embeddings.repeat_interleave(a , dim=0 ) # set timesteps __lowerCamelCase = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __lowerCamelCase = {} if accepts_offset: __lowerCamelCase = 1 self.scheduler.set_timesteps(a , **a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __lowerCamelCase , __lowerCamelCase = self.get_timesteps(a , a , self.device ) __lowerCamelCase = timesteps[:1].repeat(a ) # Preprocess image __lowerCamelCase = preprocess(a , a , a ) __lowerCamelCase = self.prepare_latents( a , a , a , text_embeddings.dtype , self.device , a ) __lowerCamelCase = preprocess(a , a , a ) __lowerCamelCase = self.prepare_latents( a , a , a , text_embeddings.dtype , self.device , a ) __lowerCamelCase = slerp(a , a , a ) if clip_guidance_scale > 0: __lowerCamelCase = self.get_clip_image_embeddings(a , a ) __lowerCamelCase = self.get_clip_image_embeddings(a , a ) __lowerCamelCase = slerp( a , a , a ) # 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 = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __lowerCamelCase = content_text_input.input_ids.shape[-1] __lowerCamelCase = self.tokenizer([''''''] , padding='''max_length''' , max_length=a , return_tensors='''pt''' ) __lowerCamelCase = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __lowerCamelCase = uncond_embeddings.repeat_interleave(a , dim=0 ) # 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 = 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 = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __lowerCamelCase = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __lowerCamelCase = torch.randn(a , generator=a , device='''cpu''' , dtype=a ).to( self.device ) else: __lowerCamelCase = torch.randn(a , generator=a , device=self.device , dtype=a ) else: if latents.shape != latents_shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) __lowerCamelCase = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __lowerCamelCase = 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 = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __lowerCamelCase = {} if accepts_eta: __lowerCamelCase = eta # check if the scheduler accepts generator __lowerCamelCase = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __lowerCamelCase = generator with self.progress_bar(total=a ): for i, t in enumerate(a ): # expand the latents if we are doing classifier free guidance __lowerCamelCase = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCamelCase = self.scheduler.scale_model_input(a , a ) # predict the noise residual __lowerCamelCase = self.unet(a , a , encoder_hidden_states=a ).sample # perform classifier free guidance if do_classifier_free_guidance: __lowerCamelCase , __lowerCamelCase = noise_pred.chunk(2 ) __lowerCamelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __lowerCamelCase = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __lowerCamelCase , __lowerCamelCase = self.cond_fn( a , a , a , a , a , a , a , ) # compute the previous noisy sample x_t -> x_t-1 __lowerCamelCase = self.scheduler.step(a , a , a , **a ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase = 1 / 0.1_82_15 * latents __lowerCamelCase = self.vae.decode(a ).sample __lowerCamelCase = (image / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __lowerCamelCase = self.numpy_to_pil(a ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=a , nsfw_content_detected=a )
67
'''simple docstring''' import os import sys __lowercase : List[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowercase : int = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[str] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoConfig.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoTokenizer.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : str , **_SCREAMING_SNAKE_CASE : Any ): return AutoTokenizer.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModel.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Union[str, Any] ): return AutoModel.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[Any] , **_SCREAMING_SNAKE_CASE : Optional[int] ): return AutoModelForCausalLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Union[str, Any] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoModelForMaskedLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Optional[Any] , **_SCREAMING_SNAKE_CASE : Any ): return AutoModelForSequenceClassification.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Any , **_SCREAMING_SNAKE_CASE : List[str] ): return AutoModelForQuestionAnswering.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
27
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """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 a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'sew-d' def __init__( self , lowercase=32 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3072 , lowercase=2 , lowercase=512 , lowercase=256 , lowercase=True , lowercase=True , lowercase=("p2c", "c2p") , lowercase="layer_norm" , lowercase="gelu_python" , lowercase=0.1 , lowercase=0.1 , lowercase=0.1 , lowercase=0.0 , lowercase=0.1 , lowercase=0.02 , lowercase=1e-7 , lowercase=1e-5 , lowercase="group" , lowercase="gelu" , lowercase=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , lowercase=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , lowercase=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , lowercase=False , lowercase=128 , lowercase=16 , lowercase=True , lowercase=0.05 , lowercase=10 , lowercase=2 , lowercase=0.0 , lowercase=10 , lowercase=0 , lowercase="mean" , lowercase=False , lowercase=False , lowercase=256 , lowercase=0 , lowercase=1 , lowercase=2 , **lowercase , ) -> str: '''simple docstring''' super().__init__(**lowercase , pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase ) A__ = hidden_size A__ = feat_extract_norm A__ = feat_extract_activation A__ = list(lowercase ) A__ = list(lowercase ) A__ = list(lowercase ) A__ = conv_bias A__ = num_conv_pos_embeddings A__ = num_conv_pos_embedding_groups A__ = len(self.conv_dim ) A__ = num_hidden_layers A__ = intermediate_size A__ = squeeze_factor A__ = max_position_embeddings A__ = position_buckets A__ = share_att_key A__ = relative_attention A__ = norm_rel_ebd A__ = list(lowercase ) A__ = hidden_act A__ = num_attention_heads A__ = hidden_dropout A__ = attention_dropout A__ = activation_dropout A__ = feat_proj_dropout A__ = final_dropout A__ = layer_norm_eps A__ = feature_layer_norm_eps A__ = initializer_range A__ = 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 A__ = apply_spec_augment A__ = mask_time_prob A__ = mask_time_length A__ = mask_time_min_masks A__ = mask_feature_prob A__ = mask_feature_length A__ = mask_feature_min_masks # ctc loss A__ = ctc_loss_reduction A__ = ctc_zero_infinity # sequence classification A__ = use_weighted_layer_sum A__ = classifier_proj_size @property def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
68
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = inspect.getfile(accelerate.test_utils ) __a : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __a : Union[str, Any] = test_metrics @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def __UpperCAmelCase ( self ): '''simple docstring''' self.test_metrics.main() @require_multi_gpu def __UpperCAmelCase ( self ): '''simple docstring''' print(f"""Found {torch.cuda.device_count()} devices.""" ) __a : List[Any] = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() )
27
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { '''facebook/levit-128S''': '''https://huggingface.co/facebook/levit-128S/resolve/main/config.json''', # See all LeViT models at https://huggingface.co/models?filter=levit } class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = "levit" def __init__( self, lowerCAmelCase__=224, lowerCAmelCase__=3, lowerCAmelCase__=3, lowerCAmelCase__=2, lowerCAmelCase__=1, lowerCAmelCase__=16, lowerCAmelCase__=[128, 256, 384], lowerCAmelCase__=[4, 8, 12], lowerCAmelCase__=[4, 4, 4], lowerCAmelCase__=[16, 16, 16], lowerCAmelCase__=0, lowerCAmelCase__=[2, 2, 2], lowerCAmelCase__=[2, 2, 2], lowerCAmelCase__=0.02, **lowerCAmelCase__, ) -> Optional[Any]: super().__init__(**lowerCAmelCase__) snake_case_ = image_size snake_case_ = num_channels snake_case_ = kernel_size snake_case_ = stride snake_case_ = padding snake_case_ = hidden_sizes snake_case_ = num_attention_heads snake_case_ = depths snake_case_ = key_dim snake_case_ = drop_path_rate snake_case_ = patch_size snake_case_ = attention_ratio snake_case_ = mlp_ratio snake_case_ = initializer_range snake_case_ = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = version.parse("1.11" ) @property def a_ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ]) @property def a_ ( self) -> float: return 1e-4
69
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): __a : Optional[Any] = tmp_path / 'file.csv' __a : Union[str, Any] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : str = tmp_path / 'malformed_file.csv' __a : int = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = tmp_path / 'csv_with_image.csv' __a : Dict = textwrap.dedent( F"""\ image {image_file} """ ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Union[str, Any] = tmp_path / 'csv_with_label.csv' __a : Any = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Dict = tmp_path / 'csv_with_int_list.csv' __a : Tuple = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): __a : int = Csv() __a : str = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_SCREAMING_SNAKE_CASE , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(_SCREAMING_SNAKE_CASE ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1] __a : Tuple = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) __a : Any = csv._generate_tables([[csv_file_with_image]] ) __a : int = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() __a : Any = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1:] __a : Optional[int] = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) __a : List[str] = csv._generate_tables([[csv_file_with_label]] ) __a : Dict = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() __a : int = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(_SCREAMING_SNAKE_CASE ) for label in labels] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda _SCREAMING_SNAKE_CASE : [int(_SCREAMING_SNAKE_CASE ) for i in x.split()]} ) __a : Any = csv._generate_tables([[csv_file_with_int_list]] ) __a : Any = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) __a : Tuple = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
27
0
'''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__ : List[Any] ={'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] =['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] =['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : str =[ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple =[ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] =[ '''TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXGLMForCausalLM''', '''TFXGLMModel''', '''TFXGLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys A__ : Optional[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure)
70
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Union[str, Any] = { 'configuration_blenderbot': [ 'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotConfig', 'BlenderbotOnnxConfig', ], 'tokenization_blenderbot': ['BlenderbotTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ['BlenderbotTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = [ 'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotForCausalLM', 'BlenderbotForConditionalGeneration', 'BlenderbotModel', 'BlenderbotPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ 'TFBlenderbotForConditionalGeneration', 'TFBlenderbotModel', 'TFBlenderbotPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Dict = [ 'FlaxBlenderbotForConditionalGeneration', 'FlaxBlenderbotModel', 'FlaxBlenderbotPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 A_ :int = get_tests_dir('''fixtures''') class __A ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =mock.Mock() __UpperCamelCase : List[Any] =500 __UpperCamelCase : List[str] ={} __UpperCamelCase : str =HTTPError __UpperCamelCase : Optional[int] ={} # Download this model to make sure it's in the cache. __UpperCamelCase : int =WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=lowerCamelCase__ ) as mock_head: __UpperCamelCase : Optional[Any] =WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # This check we did call the fake head request mock_head.assert_called() def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =WavaVecaFeatureExtractor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json' ) @is_staging_test class __A ( unittest.TestCase ): """simple docstring""" @classmethod def __lowercase ( cls ): """simple docstring""" __UpperCamelCase : Any =TOKEN HfFolder.save_token(lowerCamelCase__ ) @classmethod def __lowercase ( cls ): """simple docstring""" try: delete_repo(token=cls._token , repo_id='test-feature-extractor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-feature-extractor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-feature-extractor' ) except HTTPError: pass def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase__ ) feature_extractor.push_to_hub('test-feature-extractor' , use_auth_token=self._token ) __UpperCamelCase : List[str] =WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id='test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( lowerCamelCase__ , repo_id='test-feature-extractor' , push_to_hub=lowerCamelCase__ , use_auth_token=self._token ) __UpperCamelCase : List[Any] =WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[Any] =WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase__ ) feature_extractor.push_to_hub('valid_org/test-feature-extractor' , use_auth_token=self._token ) __UpperCamelCase : Union[str, Any] =WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( lowerCamelCase__ , repo_id='valid_org/test-feature-extractor-org' , push_to_hub=lowerCamelCase__ , use_auth_token=self._token ) __UpperCamelCase : Tuple =WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) def __lowercase ( self ): """simple docstring""" CustomFeatureExtractor.register_for_auto_class() __UpperCamelCase : Tuple =CustomFeatureExtractor.from_pretrained(lowerCamelCase__ ) feature_extractor.push_to_hub('test-dynamic-feature-extractor' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor'} , ) __UpperCamelCase : int =AutoFeatureExtractor.from_pretrained( f'{USER}/test-dynamic-feature-extractor' , trust_remote_code=lowerCamelCase__ ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , 'CustomFeatureExtractor' )
71
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase : def __init__( self , __a , __a=2 , __a=3 , __a=4 , __a=2 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=36 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=6 , __a=6 , __a=3 , __a=4 , __a=None , __a=1000 , ): '''simple docstring''' __a : Optional[Any] = parent __a : int = batch_size __a : Any = num_channels __a : Optional[int] = image_size __a : Dict = patch_size __a : int = is_training __a : Union[str, Any] = use_input_mask __a : Optional[int] = use_token_type_ids __a : Dict = use_labels __a : str = vocab_size __a : List[Any] = hidden_size __a : Union[str, Any] = num_hidden_layers __a : str = num_attention_heads __a : Union[str, Any] = intermediate_size __a : Any = hidden_act __a : List[str] = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : List[Any] = max_position_embeddings __a : Tuple = type_vocab_size __a : Any = type_sequence_label_size __a : Optional[int] = initializer_range __a : Any = coordinate_size __a : List[Any] = shape_size __a : Optional[int] = num_labels __a : Dict = num_choices __a : Union[str, Any] = scope __a : Union[str, Any] = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __a : Optional[int] = text_seq_length __a : Any = (image_size // patch_size) ** 2 + 1 __a : Dict = self.text_seq_length + self.image_seq_length def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __a : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __a : Any = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a : List[Any] = bbox[i, j, 3] __a : Tuple = bbox[i, j, 1] __a : str = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __a : int = bbox[i, j, 2] __a : Dict = bbox[i, j, 0] __a : int = tmp_coordinate __a : Optional[int] = tf.constant(__a ) __a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_input_mask: __a : Optional[Any] = random_attention_mask([self.batch_size, self.text_seq_length] ) __a : str = None if self.use_token_type_ids: __a : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __a : Optional[Any] = None __a : Optional[int] = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __a : int = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = TFLayoutLMvaModel(config=__a ) # text + image __a : List[Any] = model(__a , pixel_values=__a , training=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , training=__a , ) __a : Optional[int] = model(__a , bbox=__a , pixel_values=__a , training=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __a : Any = model(__a , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __a : str = model({'pixel_values': pixel_values} , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = TFLayoutLMvaForSequenceClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : str = self.num_labels __a : Optional[Any] = TFLayoutLMvaForTokenClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[Any] = 2 __a : Any = TFLayoutLMvaForQuestionAnswering(config=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , training=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a)) : Dict = config_and_inputs __a : Any = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) A_ = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) A_ = False A_ = False A_ = False def __UpperCAmelCase ( self , __a , __a , __a , __a , __a ): '''simple docstring''' return True def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : str = copy.deepcopy(__a ) if model_class in get_values(__a ): __a : str = { k: tf.tile(tf.expand_dims(__a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(__a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__a ): __a : Optional[int] = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : int = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __a : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Union[str, Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = TFLayoutLMvaModelTester(self ) __a : Optional[int] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) if getattr(__a , 'hf_compute_loss' , __a ): # The number of elements in the loss should be the same as the number of elements in the label __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=__a )[0] ] __a : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : Dict = prepared_for_class.pop('input_ids' ) __a : Tuple = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __a : Union[str, Any] = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __a : List[Any] = -100 __a : List[str] = tf.convert_to_tensor(__a ) __a : Any = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = model(__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __a : Tuple = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) # Get keys that were added with the _prepare_for_class function __a : Dict = prepared_for_class.keys() - inputs_dict.keys() __a : Any = inspect.signature(model.call ).parameters __a : str = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __a : List[Any] = {0: 'input_ids'} for label_key in label_keys: __a : List[Any] = signature_names.index(__a ) __a : Union[str, Any] = label_key __a : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __a : Union[str, Any] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __a : Optional[Any] = prepared_for_class[value] __a : str = tuple(__a ) # Send to model __a : Tuple = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a : Any = type self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( __a , __a , __a , __a , __a , __a , __a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = TFLayoutLMvaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__a ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __a : Tuple = self.default_image_processor __a : List[Any] = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ).pixel_values __a : Union[str, Any] = tf.constant([[1, 2]] ) __a : Optional[Any] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __a : Tuple = model(input_ids=__a , bbox=__a , pixel_values=__a , training=__a ) # verify the logits __a : List[Any] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , __a ) __a : Optional[Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , __a , atol=1E-4 ) )
27
0
"""simple docstring""" import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class __snake_case ( _lowercase): snake_case__ : Optional[Any] = (CMStochasticIterativeScheduler,) snake_case__ : Tuple = 1_0 def SCREAMING_SNAKE_CASE ( self : str , **__lowerCAmelCase : List[str] ): """simple docstring""" _lowerCamelCase : List[str] = { '''num_train_timesteps''': 2_0_1, '''sigma_min''': 0.0_02, '''sigma_max''': 80.0, } config.update(**__lowerCAmelCase ) return config def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = 1_0 _lowerCamelCase : List[str] = self.get_scheduler_config() _lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**__lowerCAmelCase ) scheduler.set_timesteps(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = scheduler.timesteps[0] _lowerCamelCase : str = scheduler.timesteps[1] _lowerCamelCase : List[Any] = self.dummy_sample _lowerCamelCase : str = 0.1 * sample _lowerCamelCase : str = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ).prev_sample _lowerCamelCase : Tuple = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : List[Any] = self.scheduler_classes[0] _lowerCamelCase : Optional[Any] = self.get_scheduler_config() _lowerCamelCase : int = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : str = 1 scheduler.set_timesteps(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = scheduler.timesteps _lowerCamelCase : Tuple = torch.manual_seed(0 ) _lowerCamelCase : int = self.dummy_model() _lowerCamelCase : Dict = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(__lowerCAmelCase ): # 1. scale model input _lowerCamelCase : Dict = scheduler.scale_model_input(__lowerCAmelCase , __lowerCAmelCase ) # 2. predict noise residual _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , __lowerCAmelCase ) # 3. predict previous sample x_t-1 _lowerCamelCase : Any = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample _lowerCamelCase : List[str] = pred_prev_sample _lowerCamelCase : int = torch.sum(torch.abs(__lowerCAmelCase ) ) _lowerCamelCase : str = torch.mean(torch.abs(__lowerCAmelCase ) ) assert abs(result_sum.item() - 1_92.76_14 ) < 1E-2 assert abs(result_mean.item() - 0.25_10 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.scheduler_classes[0] _lowerCamelCase : List[str] = self.get_scheduler_config() _lowerCamelCase : str = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : int = [1_0_6, 0] scheduler.set_timesteps(timesteps=__lowerCAmelCase ) _lowerCamelCase : str = scheduler.timesteps _lowerCamelCase : str = torch.manual_seed(0 ) _lowerCamelCase : Optional[int] = self.dummy_model() _lowerCamelCase : List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input _lowerCamelCase : Optional[Any] = scheduler.scale_model_input(__lowerCAmelCase , __lowerCAmelCase ) # 2. predict noise residual _lowerCamelCase : Optional[Any] = model(__lowerCAmelCase , __lowerCAmelCase ) # 3. predict previous sample x_t-1 _lowerCamelCase : Union[str, Any] = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample _lowerCamelCase : List[str] = pred_prev_sample _lowerCamelCase : Optional[int] = torch.sum(torch.abs(__lowerCAmelCase ) ) _lowerCamelCase : Tuple = torch.mean(torch.abs(__lowerCAmelCase ) ) assert abs(result_sum.item() - 3_47.63_57 ) < 1E-2 assert abs(result_mean.item() - 0.45_27 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.scheduler_classes[0] _lowerCamelCase : str = self.get_scheduler_config() _lowerCamelCase : List[Any] = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = [3_9, 3_0, 1_2, 1_5, 0] with self.assertRaises(__lowerCAmelCase , msg='''`timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : int = self.scheduler_classes[0] _lowerCamelCase : Any = self.get_scheduler_config() _lowerCamelCase : List[Any] = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : List[Any] = [3_9, 3_0, 1_2, 1, 0] _lowerCamelCase : Optional[Any] = len(__lowerCAmelCase ) with self.assertRaises(__lowerCAmelCase , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=__lowerCAmelCase , timesteps=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : List[Any] = self.scheduler_classes[0] _lowerCamelCase : Dict = self.get_scheduler_config() _lowerCamelCase : Dict = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : Dict = [scheduler.config.num_train_timesteps] with self.assertRaises( __lowerCAmelCase , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=__lowerCAmelCase )
72
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"""{test_file} instead.""" ) __a : Tuple = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __a : List[str] = components[:-1] + [test_fn.replace('.py' , '' )] __a : Optional[Any] = '.'.join(_SCREAMING_SNAKE_CASE ) return test_module_path def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = get_module_path(_SCREAMING_SNAKE_CASE ) __a : Dict = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = [] __a : List[str] = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : Any = [] __a : str = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): __a : int = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'all_model_classes' , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Tuple = test_class() if hasattr(_SCREAMING_SNAKE_CASE , 'setUp' ): test.setUp() __a : List[Any] = None if hasattr(_SCREAMING_SNAKE_CASE , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __a : List[str] = test.model_tester.__class__ return model_tester def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] ): __a : List[Any] = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [] for test_class in test_classes: __a : Any = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : str = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
27
0
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) a =logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : List[Any] = git.Repo(search_parent_directories=lowerCamelCase__ ) __lowerCamelCase : str = { 'repo_id': str(lowerCamelCase__ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), } with open(os.path.join(lowerCamelCase__ , 'git_log.json' ) , 'w' ) as f: json.dump(lowerCamelCase__ , lowerCamelCase__ , indent=4 ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if params.n_gpu <= 0: __lowerCamelCase : Any = 0 __lowerCamelCase : Union[str, Any] = -1 __lowerCamelCase : str = True __lowerCamelCase : List[Any] = False return assert torch.cuda.is_available() logger.info('Initializing GPUs' ) if params.n_gpu > 1: assert params.local_rank != -1 __lowerCamelCase : Tuple = int(os.environ['WORLD_SIZE'] ) __lowerCamelCase : int = int(os.environ['N_GPU_NODE'] ) __lowerCamelCase : Dict = int(os.environ['RANK'] ) # number of nodes / node ID __lowerCamelCase : Dict = params.world_size // params.n_gpu_per_node __lowerCamelCase : int = params.global_rank // params.n_gpu_per_node __lowerCamelCase : Union[str, Any] = True assert params.n_nodes == int(os.environ['N_NODES'] ) assert params.node_id == int(os.environ['NODE_RANK'] ) # local job (single GPU) else: assert params.local_rank == -1 __lowerCamelCase : int = 1 __lowerCamelCase : Dict = 0 __lowerCamelCase : Tuple = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode __lowerCamelCase : List[str] = params.node_id == 0 and params.local_rank == 0 __lowerCamelCase : Dict = params.n_nodes > 1 # summary __lowerCamelCase : List[str] = F"--- Global rank: {params.global_rank} - " logger.info(PREFIX + 'Number of nodes: %i' % params.n_nodes ) logger.info(PREFIX + 'Node ID : %i' % params.node_id ) logger.info(PREFIX + 'Local rank : %i' % params.local_rank ) logger.info(PREFIX + 'World size : %i' % params.world_size ) logger.info(PREFIX + 'GPUs per node : %i' % params.n_gpu_per_node ) logger.info(PREFIX + 'Master : %s' % str(params.is_master ) ) logger.info(PREFIX + 'Multi-node : %s' % str(params.multi_node ) ) logger.info(PREFIX + 'Multi-GPU : %s' % str(params.multi_gpu ) ) logger.info(PREFIX + 'Hostname : %s' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('Initializing PyTorch distributed' ) torch.distributed.init_process_group( init_method='env://' , backend='nccl' , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Union[str, Any]: np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
73
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = StableDiffusionInpaintPipeline A_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS A_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS A_ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess A_ = frozenset([] ) def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__a , ) __a : str = PNDMScheduler(skip_prk_steps=__a ) torch.manual_seed(0 ) __a : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __a : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __a : Dict = CLIPTextModel(__a ) __a : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __a : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCAmelCase ( self , __a , __a=0 ): '''simple docstring''' __a : Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) __a : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a : Tuple = Image.fromarray(np.uinta(__a ) ).convert('RGB' ).resize((64, 64) ) __a : Tuple = Image.fromarray(np.uinta(image + 4 ) ).convert('RGB' ).resize((64, 64) ) if str(__a ).startswith('mps' ): __a : Any = torch.manual_seed(__a ) else: __a : str = torch.Generator(device=__a ).manual_seed(__a ) __a : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': init_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator __a : str = self.get_dummy_components() __a : Union[str, Any] = StableDiffusionInpaintPipeline(**__a ) __a : List[Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) __a : List[Any] = self.get_dummy_inputs(__a ) __a : Dict = sd_pipe(**__a ).images __a : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : List[Any] = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench.npy' ) __a : Optional[int] = 'stabilityai/stable-diffusion-2-inpainting' __a : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained(__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Dict = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : int = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench_fp16.npy' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : List[str] = StableDiffusionInpaintPipeline.from_pretrained( __a , torch_dtype=torch.floataa , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Union[str, Any] = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : int = torch.manual_seed(0 ) __a : Optional[Any] = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : int = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def __UpperCAmelCase ( self ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __a : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : Any = PNDMScheduler.from_pretrained(__a , subfolder='scheduler' ) __a : str = StableDiffusionInpaintPipeline.from_pretrained( __a , safety_checker=__a , scheduler=__a , torch_dtype=torch.floataa , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __a : str = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : str = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , num_inference_steps=2 , output_type='np' , ) __a : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
27
0
"""simple docstring""" from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse('''3.8'''): import importlib_metadata else: import importlib.metadata as importlib_metadata _lowercase = '''''' if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''): class lowerCAmelCase_ ( tr.AbstractTransform ): '''simple docstring''' def __init__( self : str ,A_ : str = " " ) -> Tuple: A = sentence_delimiter def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ) -> Optional[int]: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[str] ) -> Any: A = [] for sent_idx, sentence in enumerate(A_ ): chars.extend(self.process_string(A_ ) ) if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(A_ ) - 1: chars.append(self.sentence_delimiter ) return chars _lowercase = tr.Compose( [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)] ) else: _lowercase = tr.Compose( [ tr.RemoveMultipleSpaces(), tr.Strip(), tr.ReduceToSingleSentence(SENTENCE_DELIMITER), tr.ReduceToListOfListOfChars(), ] ) _lowercase = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' _lowercase = '''\ Character error rate (CER) is a common metric of the performance of an automatic speech recognition system. CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information. Character error rate can be computed as: CER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct characters, N is the number of characters in the reference (N=S+D+C). CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the performance of the ASR system with a CER of 0 being a perfect score. ''' _lowercase = ''' Computes CER score of transcribed segments against references. Args: references: list of references for each speech input. predictions: list of transcribtions to score. concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result. Returns: (float): the character error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> cer = datasets.load_metric("cer") >>> cer_score = cer.compute(predictions=predictions, references=references) >>> print(cer_score) 0.34146341463414637 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: 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/jitsi/jiwer/'] ,reference_urls=[ 'https://en.wikipedia.org/wiki/Word_error_rate', 'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates', ] ,) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : str=False ) -> Tuple: if concatenate_texts: return jiwer.compute_measures( A_ ,A_ ,truth_transform=A_ ,hypothesis_transform=A_ ,)["wer"] A = 0 A = 0 for prediction, reference in zip(A_ ,A_ ): A = jiwer.compute_measures( A_ ,A_ ,truth_transform=A_ ,hypothesis_transform=A_ ,) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
74
'''simple docstring''' import requests __lowercase : Tuple = '' # <-- Put your OpenWeatherMap appid here! __lowercase : Tuple = 'https://api.openweathermap.org/data/2.5/' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Chicago" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'weather' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Kolkata, India" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : float = 5_5.6_8 , _SCREAMING_SNAKE_CASE : float = 1_2.5_7 , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowercase : Dict = input('Enter a location:').strip() if location: pprint(current_weather(location)) else: break
27
0
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a_ : str = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class __UpperCamelCase ( unittest.TestCase ): def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = True, ): """simple docstring""" lowerCamelCase_ =[file for file in os.listdir(lowerCAmelCase ) if os.path.isfile(os.path.join(lowerCAmelCase, lowerCAmelCase ) )] if identifier is not None: lowerCamelCase_ =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(lowerCAmelCase, lowerCAmelCase ): for n_ in n_identifier: lowerCamelCase_ =[file for file in files if n_ not in file] else: lowerCamelCase_ =[file for file in files if n_identifier not in file] lowerCamelCase_ =ignore_files or [] ignore_files.append('''__init__.py''' ) lowerCamelCase_ =[file for file in files if file not in ignore_files] for file in files: # Open all files print('''Testing''', lowerCAmelCase ) if only_modules: lowerCamelCase_ =file.split('''.''' )[0] try: lowerCamelCase_ =getattr(lowerCAmelCase, lowerCAmelCase ) lowerCamelCase_ =doctest.DocTestSuite(lowerCAmelCase ) lowerCamelCase_ =unittest.TextTestRunner().run(lowerCAmelCase ) self.assertIs(len(result.failures ), 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: lowerCamelCase_ =doctest.testfile(str('''..''' / directory / file ), optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed, 0 ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =Path('''src/transformers''' ) lowerCamelCase_ ='''modeling''' lowerCamelCase_ =[ '''modeling_ctrl.py''', '''modeling_tf_ctrl.py''', ] self.analyze_directory(lowerCAmelCase, identifier=lowerCAmelCase, ignore_files=lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =Path('''src/transformers''' ) lowerCamelCase_ ='''tokenization''' self.analyze_directory(lowerCAmelCase, identifier=lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =Path('''src/transformers''' ) lowerCamelCase_ ='''configuration''' self.analyze_directory(lowerCAmelCase, identifier=lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =Path('''src/transformers''' ) lowerCamelCase_ =['''configuration''', '''modeling''', '''tokenization'''] self.analyze_directory(lowerCAmelCase, n_identifier=lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =Path('''docs/source''' ) lowerCamelCase_ =['''favicon.ico'''] self.analyze_directory(lowerCAmelCase, ignore_files=lowerCAmelCase, only_modules=lowerCAmelCase )
75
'''simple docstring''' import torch from transformers import AutoModel class __UpperCamelCase ( torch.nn.Module ): def __init__( self , __a="sayef/fsner-bert-base-uncased" ): '''simple docstring''' super(__a , self ).__init__() __a : Tuple = AutoModel.from_pretrained(__a , return_dict=__a ) __a : int = torch.nn.CosineSimilarity(3 , 1E-0_8 ) __a : Union[str, Any] = torch.nn.Softmax(dim=1 ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return self.bert(**__a ).last_hidden_state def __UpperCAmelCase ( self , __a ): '''simple docstring''' return token_embeddings.sum(2 , keepdim=__a ) def __UpperCAmelCase ( self , __a , __a , __a=1 ): '''simple docstring''' return self.softmax(T * self.cos(__a , __a ) ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : str = W_supports['sizes'].tolist() __a : Union[str, Any] = W_supports['start_token_id'].item() __a : Any = W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __a : Tuple = self.BERT(**__a ) __a : str = self.BERT(**__a ) __a : Any = None __a : Dict = None __a : Dict = W_supports['input_ids'] == start_token_id __a : Union[str, Any] = W_supports['input_ids'] == end_token_id for i, size in enumerate(__a ): if i == 0: __a : Optional[int] = 0 else: __a : Union[str, Any] = support_sizes[i - 1] __a : int = S[s : s + size][start_token_masks[s : s + size]] __a : Union[str, Any] = S[s : s + size][end_token_masks[s : s + size]] __a : Tuple = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __a : Dict = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __a : str = torch.vstack((p_starts, p_start) ) __a : str = torch.vstack((p_ends, p_end) ) else: __a : List[str] = p_start __a : int = p_end return p_starts, p_ends
27
0
def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = int(_a) if n_element < 1: SCREAMING_SNAKE_CASE : Optional[int] = ValueError("a should be a positive number") raise my_error SCREAMING_SNAKE_CASE : Union[str, Any] = [1] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = (0, 0, 0) SCREAMING_SNAKE_CASE : Union[str, Any] = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5)) index += 1 return hamming_list if __name__ == "__main__": a_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') a_ = hamming(int(n)) print('-----------------------------------------------------') print(F'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
76
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 35 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : Optional[Any] = x_den * y_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : Optional[int] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : List[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Any = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Optional[int] = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 __a : int = x_num * y_num __a : Optional[Any] = x_den * y_num + x_num * y_den __a : Tuple = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : List[Any] = x_num * x_num * y_num * y_num __a : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : Optional[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
27
0
"""simple docstring""" import gc import threading import time import psutil import torch class UpperCAmelCase_ : def __init__( self ) -> Union[str, Any]: lowercase__ : Dict = psutil.Process() lowercase__ : int = False def _UpperCAmelCase ( self ) -> str: lowercase__ : List[str] = -1 while True: lowercase__ : str = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ : List[Any] = True lowercase__ : Optional[int] = threading.Thread(target=self.peak_monitor ) lowercase__ : List[str] = True self.thread.start() def _UpperCAmelCase ( self ) -> List[str]: lowercase__ : Optional[int] = False self.thread.join() return self.cpu_memory_peak _UpperCamelCase : Optional[Any] = PeakCPUMemory() def a_ ( ): '''simple docstring''' lowercase__ : Any = {'time': time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem lowercase__ : Tuple = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): lowercase__ : Union[str, Any] = torch.cuda.memory_allocated(_lowerCAmelCase ) torch.cuda.reset_peak_memory_stats() return measures def a_ ( _lowerCAmelCase : Tuple ): '''simple docstring''' lowercase__ : int = {'time': time.time() - start_measures['time']} gc.collect() torch.cuda.empty_cache() # CPU mem lowercase__ : Union[str, Any] = (psutil.Process().memory_info().rss - start_measures['cpu']) / 2**20 lowercase__ : Any = (cpu_peak_tracker.stop() - start_measures['cpu']) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): lowercase__ : Optional[int] = (torch.cuda.memory_allocated(_lowerCAmelCase ) - start_measures[str(_lowerCAmelCase )]) / 2**20 lowercase__ : Union[str, Any] = (torch.cuda.max_memory_allocated(_lowerCAmelCase ) - start_measures[str(_lowerCAmelCase )]) / 2**20 return measures def a_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Any ): '''simple docstring''' print(f"""{description}:""" ) print(f"""- Time: {measures["time"]:.2f}s""" ) for i in range(torch.cuda.device_count() ): print(f"""- GPU {i} allocated: {measures[str(_lowerCAmelCase )]:.2f}MiB""" ) lowercase__ : List[Any] = measures[f"""{i}-peak"""] print(f"""- GPU {i} peak: {peak:.2f}MiB""" ) print(f"""- CPU RAM allocated: {measures["cpu"]:.2f}MiB""" ) print(f"""- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB""" )
77
'''simple docstring''' import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): @property def __UpperCAmelCase ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ort.SessionOptions() __a : Dict = False return options def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) __a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default __a : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__a , feature_extractor=__a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__a ) __a : Tuple = 'A red cat sitting on a park bench' __a : int = np.random.RandomState(0 ) __a : Tuple = pipe( prompt=__a , image=__a , mask_image=__a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=__a , output_type='np' , ) __a : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
27
0
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :Optional[Any] , lowercase_ :int , lowercase_ :Tuple=13 , lowercase_ :Any=7 , lowercase_ :List[str]=True , lowercase_ :Optional[int]=True , lowercase_ :str=False , lowercase_ :Optional[int]=True , lowercase_ :Union[str, Any]=99 , lowercase_ :Optional[int]=32 , lowercase_ :int=5 , lowercase_ :int=4 , lowercase_ :Optional[int]=64 , lowercase_ :Union[str, Any]="gelu" , lowercase_ :Union[str, Any]=0.1 , lowercase_ :List[Any]=0.1 , lowercase_ :Union[str, Any]=5_12 , lowercase_ :Tuple=16 , lowercase_ :Union[str, Any]=2 , lowercase_ :Optional[Any]=0.02 , lowercase_ :Union[str, Any]=3 , lowercase_ :int=4 , lowercase_ :Any=None , lowercase_ :Any=2 , lowercase_ :List[Any]=2 , lowercase_ :Optional[Any]=2 , lowercase_ :Any=2 , lowercase_ :int=4 , lowercase_ :Optional[int]=1 , ) -> int: UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope UpperCAmelCase = q_groups UpperCAmelCase = k_groups UpperCAmelCase = v_groups UpperCAmelCase = post_attention_groups UpperCAmelCase = intermediate_groups UpperCAmelCase = output_groups def UpperCAmelCase__ ( self :Optional[Any] ) -> Union[str, Any]: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self :Optional[int] ) -> Optional[Any]: return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def UpperCAmelCase__ ( self :Optional[Any] , lowercase_ :List[str] , lowercase_ :Optional[Any] , lowercase_ :Tuple , lowercase_ :Any , lowercase_ :Dict , lowercase_ :Tuple ) -> str: UpperCAmelCase = SqueezeBertModel(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase = model(lowercase_ , lowercase_ ) UpperCAmelCase = model(lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self :List[Any] , lowercase_ :Optional[int] , lowercase_ :str , lowercase_ :Tuple , lowercase_ :List[Any] , lowercase_ :Dict , lowercase_ :Any ) -> int: UpperCAmelCase = SqueezeBertForMaskedLM(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase = model(lowercase_ , attention_mask=lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self :List[str] , lowercase_ :List[Any] , lowercase_ :Optional[int] , lowercase_ :Union[str, Any] , lowercase_ :Optional[int] , lowercase_ :Dict , lowercase_ :List[str] ) -> Dict: UpperCAmelCase = SqueezeBertForQuestionAnswering(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase = model( lowercase_ , attention_mask=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase__ ( self :List[Any] , lowercase_ :str , lowercase_ :List[str] , lowercase_ :int , lowercase_ :str , lowercase_ :Optional[int] , lowercase_ :Union[str, Any] ) -> int: UpperCAmelCase = self.num_labels UpperCAmelCase = SqueezeBertForSequenceClassification(lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase = model(lowercase_ , attention_mask=lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self :List[str] , lowercase_ :List[str] , lowercase_ :Any , lowercase_ :Any , lowercase_ :Dict , lowercase_ :Optional[int] , lowercase_ :Tuple ) -> Any: UpperCAmelCase = self.num_labels UpperCAmelCase = SqueezeBertForTokenClassification(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase = model(lowercase_ , attention_mask=lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self :int , lowercase_ :Dict , lowercase_ :Any , lowercase_ :Tuple , lowercase_ :Optional[Any] , lowercase_ :int , lowercase_ :str ) -> int: UpperCAmelCase = self.num_choices UpperCAmelCase = SqueezeBertForMultipleChoice(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = model( lowercase_ , attention_mask=lowercase_ , labels=lowercase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase__ ( self :Optional[Any] ) -> Tuple: UpperCAmelCase = self.prepare_config_and_inputs() ((UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase)) = config_and_inputs UpperCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCamelCase = ( { """feature-extraction""": SqueezeBertModel, """fill-mask""": SqueezeBertForMaskedLM, """question-answering""": SqueezeBertForQuestionAnswering, """text-classification""": SqueezeBertForSequenceClassification, """token-classification""": SqueezeBertForTokenClassification, """zero-shot""": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = False def UpperCAmelCase__ ( self :str ) -> Dict: UpperCAmelCase = SqueezeBertModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=lowercase_ , dim=37 ) def UpperCAmelCase__ ( self :int ) -> Dict: self.config_tester.run_common_tests() def UpperCAmelCase__ ( self :List[str] ) -> Tuple: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*lowercase_ ) def UpperCAmelCase__ ( self :Optional[Any] ) -> List[str]: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*lowercase_ ) def UpperCAmelCase__ ( self :List[Any] ) -> Dict: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*lowercase_ ) def UpperCAmelCase__ ( self :str ) -> Union[str, Any]: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*lowercase_ ) def UpperCAmelCase__ ( self :List[Any] ) -> Optional[Any]: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*lowercase_ ) def UpperCAmelCase__ ( self :List[str] ) -> Any: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*lowercase_ ) @slow def UpperCAmelCase__ ( self :Dict ) -> List[str]: for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = SqueezeBertModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) @require_sentencepiece @require_tokenizers @require_torch class A_ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self :Tuple ) -> int: UpperCAmelCase = SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) UpperCAmelCase = torch.tensor([[1, 2_94_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 13, 15_88, 2]] ) UpperCAmelCase = model(lowercase_ )[0] UpperCAmelCase = torch.Size((1, 3) ) self.assertEqual(output.shape , lowercase_ ) UpperCAmelCase = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(lowercase_ , lowercase_ , atol=1E-4 ) )
78
'''simple docstring''' import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowercase : Dict = 16 __lowercase : List[Any] = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return int(x / 2**20 ) class __UpperCamelCase : def __enter__( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero __a : Optional[int] = torch.cuda.memory_allocated() return self def __exit__( self , *__a ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() __a : Dict = torch.cuda.memory_allocated() __a : List[Any] = torch.cuda.max_memory_allocated() __a : Tuple = bamb(self.end - self.begin ) __a : Tuple = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def lowerCamelCase (_SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : int = 16 , _SCREAMING_SNAKE_CASE : str = "bert-base-cased" , _SCREAMING_SNAKE_CASE : int = 320 , _SCREAMING_SNAKE_CASE : int = 160 , ): __a : int = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : List[Any] = load_dataset( 'glue' , 'mrpc' , split={'train': F"""train[:{n_train}]""", 'validation': F"""validation[:{n_val}]"""} ) def tokenize_function(_SCREAMING_SNAKE_CASE : Tuple ): # max_length=None => use the model max length (it's actually the default) __a : Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a : List[str] = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=_SCREAMING_SNAKE_CASE ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : Tuple = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. __a : int = DataLoader( tokenized_datasets['train'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) __a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): # Initialize accelerator __a : str = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : Dict = config['lr'] __a : str = int(config['num_epochs'] ) __a : Optional[int] = int(config['seed'] ) __a : Any = int(config['batch_size'] ) __a : List[str] = args.model_name_or_path set_seed(_SCREAMING_SNAKE_CASE ) __a , __a : int = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : Optional[int] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE ) # Instantiate optimizer __a : Optional[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a : Optional[Any] = optimizer_cls(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) if accelerator.state.deepspeed_plugin is not None: __a : int = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: __a : Union[str, Any] = 1 __a : Tuple = (len(_SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a : str = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=0 , num_training_steps=_SCREAMING_SNAKE_CASE , ) else: __a : List[Any] = DummyScheduler(_SCREAMING_SNAKE_CASE , total_num_steps=_SCREAMING_SNAKE_CASE , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a : Optional[Any] = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # We need to keep track of how many total steps we have iterated over __a : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly __a : Dict = 0 # Now we train the model __a : str = {} for epoch in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): __a : List[Any] = model(**_SCREAMING_SNAKE_CASE ) __a : str = outputs.loss __a : str = loss / gradient_accumulation_steps accelerator.backward(_SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin ) ) ) accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used ) ) accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked ) ) accelerator.print( 'Total Peak Memory consumed during the train (max): {}'.format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) __a : List[Any] = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'peak_memory_utilization.json' ) , 'w' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : int = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=_SCREAMING_SNAKE_CASE , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_SCREAMING_SNAKE_CASE , ) parser.add_argument( '--output_dir' , type=_SCREAMING_SNAKE_CASE , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--peak_memory_upper_bound' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.' , ) parser.add_argument( '--n_train' , type=_SCREAMING_SNAKE_CASE , default=320 , help='Number of training examples to use.' , ) parser.add_argument( '--n_val' , type=_SCREAMING_SNAKE_CASE , default=160 , help='Number of validation examples to use.' , ) parser.add_argument( '--num_epochs' , type=_SCREAMING_SNAKE_CASE , default=1 , help='Number of train epochs.' , ) __a : List[str] = parser.parse_args() __a : List[Any] = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
27
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor lowerCamelCase_ = logging.get_logger(__name__) class _UpperCAmelCase ( snake_case_ ): """simple docstring""" def __init__( self : List[Any] , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Tuple ): '''simple docstring''' warnings.warn( "The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use LayoutLMv2ImageProcessor instead." , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
79
'''simple docstring''' import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer __lowercase : List[Any] = 'bart' __lowercase : Union[str, Any] = True @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : List[Any] = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) __a : Dict = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) __a : Optional[int] = qar_model.eval() else: __a , __a : str = (None, None) if MODEL_TYPE == "bart": __a : Union[str, Any] = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) __a : int = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) __a : Optional[Any] = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) __a : str = sas_model.eval() else: __a , __a : Tuple = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): if LOAD_DENSE_INDEX: __a : Optional[Any] = faiss.StandardGpuResources() __a : Dict = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] __a : int = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 128) , ) __a : int = faiss.IndexFlatIP(128 ) __a : Any = faiss.index_cpu_to_gpu(_SCREAMING_SNAKE_CASE , 1 , _SCREAMING_SNAKE_CASE ) wikiaab_gpu_index_flat.add(_SCREAMING_SNAKE_CASE ) # TODO fix for larger GPU else: __a , __a : str = (None, None) __a : Optional[int] = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : Dict = datasets.load_dataset('eli5' , name='LFQA_reddit' ) __a : Dict = elia['train_eli5'] __a : Optional[int] = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 128) ) __a : str = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(_SCREAMING_SNAKE_CASE ) return (elia_train, eli5_train_q_index) __lowercase , __lowercase , __lowercase : Any = load_indexes() __lowercase , __lowercase , __lowercase , __lowercase : Dict = load_models() __lowercase , __lowercase : int = load_train_data() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str]=10 ): __a : Optional[int] = embed_questions_for_retrieval([question] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a , __a : Union[str, Any] = eli5_train_q_index.search(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [elia_train[int(_SCREAMING_SNAKE_CASE )] for i in I[0]] return nn_examples def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : str="wiki40b" , _SCREAMING_SNAKE_CASE : List[str]="dense" , _SCREAMING_SNAKE_CASE : Any=10 ): if source == "none": __a , __a : Any = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": __a , __a : str = query_qa_dense_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a , __a : Union[str, Any] = query_es_index( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index_name='english_wiki40b_snippets_100w' , n_results=_SCREAMING_SNAKE_CASE , ) __a : Dict = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] __a : Any = 'question: {} context: {}'.format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda _SCREAMING_SNAKE_CASE : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _SCREAMING_SNAKE_CASE : None), } ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Dict=64 , _SCREAMING_SNAKE_CASE : Dict=256 , _SCREAMING_SNAKE_CASE : Any=False , _SCREAMING_SNAKE_CASE : Tuple=2 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0.9_5 , _SCREAMING_SNAKE_CASE : str=0.8 ): with torch.no_grad(): __a : Union[str, Any] = qa_sas_generate( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , num_answers=1 , num_beams=_SCREAMING_SNAKE_CASE , min_len=_SCREAMING_SNAKE_CASE , max_len=_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE , temp=_SCREAMING_SNAKE_CASE , top_p=_SCREAMING_SNAKE_CASE , top_k=_SCREAMING_SNAKE_CASE , max_input_length=1_024 , device='cuda:0' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar __lowercase : Optional[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' __lowercase : str = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia __lowercase : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) __lowercase : Dict = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] __lowercase : Union[str, Any] = st.sidebar.checkbox('Demo options') if demo_options: __lowercase : Any = st.sidebar.selectbox( '', action_list, index=3, ) __lowercase : Tuple = action_list.index(action_st) __lowercase : Tuple = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) __lowercase : List[Any] = show_type == 'Show full text of passages' else: __lowercase : int = 3 __lowercase : str = True __lowercase : Tuple = st.sidebar.checkbox('Retrieval options') if retrieval_options: __lowercase : List[Any] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) __lowercase : Union[str, Any] = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: __lowercase : str = 'wiki40b' __lowercase : List[Any] = 'dense' __lowercase : Dict = 'beam' __lowercase : Optional[int] = 2 __lowercase : List[str] = 64 __lowercase : Tuple = 2_56 __lowercase : List[str] = None __lowercase : Tuple = None __lowercase : List[Any] = st.sidebar.checkbox('Generation options') if generate_options: __lowercase : Optional[Any] = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) __lowercase : List[Any] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) __lowercase : Tuple = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=2_56, value=64, step=8, format=None, key=None ) __lowercase : int = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None ) if sampled == "beam": __lowercase : Any = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: __lowercase : Dict = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) __lowercase : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) __lowercase : List[str] = None # start main text __lowercase : int = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] __lowercase : Optional[int] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": __lowercase : Any = st.text_input('Enter your question here:', '') else: __lowercase : Any = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": __lowercase , __lowercase : Optional[int] = make_support(question, source=wiki_source, method='dense', n_results=10) __lowercase , __lowercase : List[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) __lowercase : Optional[int] = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] __lowercase : str = support_list[:10] __lowercase : Optional[int] = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: __lowercase , __lowercase : Optional[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: __lowercase , __lowercase : int = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): __lowercase : str = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) __lowercase : Any = res[1].strip() if sec_titles == "": __lowercase : List[str] = '[{}]({})'.format(res[0], wiki_url) else: __lowercase : Union[str, Any] = sec_titles.split(' & ') __lowercase : str = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: __lowercase : str = find_nearest_training(question) __lowercase : Optional[int] = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) __lowercase : Any = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) __lowercase : List[Any] = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
27
0
'''simple docstring''' import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class lowercase_ ( pl.LightningModule ): def __init__( self , a ): super().__init__() UpperCamelCase__ = model UpperCamelCase__ = 2 UpperCamelCase__ = nn.Linear(self.model.config.hidden_size , self.num_labels ) def __a ( self ): pass def _UpperCamelCase ( __A , __A , __A ) -> str: '''simple docstring''' UpperCamelCase__ = LongformerModel.from_pretrained(__A ) UpperCamelCase__ = LightningModel(__A ) UpperCamelCase__ = torch.load(__A , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model UpperCamelCase__ = LongformerForQuestionAnswering.from_pretrained(__A ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__A ) print(F'''Conversion successful. Model saved under {pytorch_dump_folder_path}''' ) if __name__ == "__main__": a__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--longformer_model', default=None, type=str, required=True, help='model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.', ) parser.add_argument( '--longformer_question_answering_ckpt_path', default=None, type=str, required=True, help='Path the official PyTorch Lightning Checkpoint.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a__ : str = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
80
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __lowercase : Tuple = logging.get_logger(__name__) __lowercase : List[Any] = torch.device('cpu') def lowerCamelCase (): __a : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __a : Tuple = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0, 8.8_6_8_5e-0_1, 2.4_3_6_0e-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6e-0_1, 2.3_4_7_8e-0_1, -1.6_9_6_3e0_0, -1.7_3_8_1e0_0, -8.6_3_3_7e-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8e-0_1, -4.7_4_2_9e-0_1, -1.0_8_9_7e0_0, -1.0_2_4_8e0_0, 3.5_5_2_3e-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0e-0_1, 2.4_2_1_1e-0_1, -6.0_1_8_5e-0_1, -8.2_7_8_9e-0_1, -6.0_4_4_6e-0_2] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : int = dct.pop(_SCREAMING_SNAKE_CASE ) __a : Tuple = val def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : Dict = [] for k in state_dict.keys(): __a : List[Any] = k if ".pwconv" in k: __a : List[Any] = k_new.replace('.pwconv' , '.point_wise_conv' ) if ".dwconv" in k: __a : Dict = k_new.replace('.dwconv' , '.depth_wise_conv' ) if ".Proj." in k: __a : Optional[int] = k_new.replace('.Proj.' , '.proj.' ) if "patch_embed" in k_new: __a : List[Any] = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' ) if "network" in k_new: __a : Union[str, Any] = k_new.split('.' ) if ls[2].isdigit(): __a : Union[str, Any] = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] ) else: __a : Union[str, Any] = k_new.replace('network' , 'swiftformer.encoder.network' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Union[str, Any] = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size __a : List[str] = 1_000 __a : Tuple = 'huggingface/label-files' __a : str = 'imagenet-1k-id2label.json' __a : Dict = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) __a : Optional[int] = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a : Any = idalabel __a : str = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": __a : Dict = [3, 3, 6, 4] __a : int = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": __a : Dict = [3, 3, 9, 6] __a : List[str] = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": __a : Dict = [4, 3, 10, 5] __a : Optional[int] = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": __a : Tuple = [4, 4, 12, 6] __a : Dict = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('https' ): __a : List[Any] = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE ) else: __a : Union[str, Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) __a : Optional[Any] = checkpoint __a : Dict = create_rename_keys(_SCREAMING_SNAKE_CASE ) for rename_key_src, rename_key_dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model __a : Tuple = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval() hf_model.load_state_dict(_SCREAMING_SNAKE_CASE ) # prepare test inputs __a : Tuple = prepare_img() __a : str = ViTImageProcessor.from_pretrained('preprocessor_config' ) __a : Tuple = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # compare outputs from both models __a : List[Any] = get_expected_output(_SCREAMING_SNAKE_CASE ) __a : Dict = hf_model(inputs['pixel_values'] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swiftformer_name', default='swiftformer_xs', choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'], type=str, help='Name of the SwiftFormer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='./converted_outputs/', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.') __lowercase : Tuple = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
27
0
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging lowerCamelCase_ : int = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A ) -> str: super().__init__() a =nn.ModuleList(__A ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A = None , __A = None , __A = None , __A = None , __A = False , __A = True , ) -> Union[ControlNetOutput, Tuple]: for i, (image, scale, controlnet) in enumerate(zip(__A , __A , self.nets ) ): a , a =controlnet( __A , __A , __A , __A , __A , __A , __A , __A , __A , __A , __A , ) # merge samples if i == 0: a , a =down_samples, mid_sample else: a =[ samples_prev + samples_curr for samples_prev, samples_curr in zip(__A , __A ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE ( self , __A , __A = True , __A = None , __A = False , __A = None , ) -> List[Any]: a =0 a =save_directory for controlnet in self.nets: controlnet.save_pretrained( __A , is_main_process=__A , save_function=__A , safe_serialization=__A , variant=__A , ) idx += 1 a =model_path_to_save + f'''_{idx}''' @classmethod def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> int: a =0 a =[] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... a =pretrained_model_path while os.path.isdir(__A ): a =ControlNetModel.from_pretrained(__A , **__A ) controlnets.append(__A ) idx += 1 a =pretrained_model_path + f'''_{idx}''' logger.info(f'''{len(__A )} controlnets loaded from {pretrained_model_path}.''' ) if len(__A ) == 0: raise ValueError( f'''No ControlNets found under {os.path.dirname(__A )}. Expected at least {pretrained_model_path + "_0"}.''' ) return cls(__A )
81
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __lowercase : Dict = logging.get_logger(__name__) __lowercase : Optional[Any] = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "umt5" A_ = ["past_key_values"] def __init__( self , __a=25_0112 , __a=512 , __a=64 , __a=1024 , __a=8 , __a=None , __a=6 , __a=32 , __a=128 , __a=0.1 , __a=1E-6 , __a=1.0 , __a="gated-gelu" , __a=True , __a=True , __a="T5Tokenizer" , __a=True , __a=0 , __a=1 , __a=0 , **__a , ): '''simple docstring''' super().__init__( is_encoder_decoder=__a , tokenizer_class=__a , tie_word_embeddings=__a , pad_token_id=__a , eos_token_id=__a , decoder_start_token_id=__a , **__a , ) __a : Any = vocab_size __a : Any = d_model __a : str = d_kv __a : Dict = d_ff __a : Union[str, Any] = num_layers __a : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __a : Optional[int] = num_heads __a : Tuple = relative_attention_num_buckets __a : Optional[Any] = relative_attention_max_distance __a : Optional[int] = dropout_rate __a : List[Any] = layer_norm_epsilon __a : int = initializer_factor __a : Union[str, Any] = feed_forward_proj __a : Any = use_cache __a : List[Any] = self.feed_forward_proj.split('-' ) __a : Dict = act_info[-1] __a : Dict = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) if feed_forward_proj == "gated-gelu": __a : Optional[int] = 'gelu_new' @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.d_model @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_heads @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.num_layers class __UpperCamelCase ( lowerCAmelCase_ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __a : Dict = 'past_encoder_sequence + sequence' __a : Tuple = {0: 'batch'} __a : Tuple = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __a : List[Any] = {0: 'batch', 1: 'decoder_sequence'} __a : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __UpperCAmelCase ( self ): '''simple docstring''' return 13 @property def __UpperCAmelCase ( self ): '''simple docstring''' return 5E-4
27
0
from __future__ import annotations import math def _UpperCAmelCase ( snake_case ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _UpperCAmelCase ( snake_case ): """simple docstring""" _lowerCAmelCase = str(snake_case ) _lowerCAmelCase = [n] for i in range(1 , len(snake_case ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _UpperCAmelCase ( snake_case ): """simple docstring""" if len(str(snake_case ) ) > 3: if not is_prime(int(str(snake_case )[-3:] ) ) or not is_prime(int(str(snake_case )[:3] ) ): return False return True def _UpperCAmelCase ( snake_case = 11 ): """simple docstring""" _lowerCAmelCase = [] _lowerCAmelCase = 13 while len(snake_case ) != count: if validate(snake_case ): _lowerCAmelCase = list_truncated_nums(snake_case ) if all(is_prime(snake_case ) for i in list_nums ): list_truncated_primes.append(snake_case ) num += 2 return list_truncated_primes def _UpperCAmelCase ( ): """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
82
'''simple docstring''' import requests from bsa import BeautifulSoup def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "https://www.worldometers.info/coronavirus" ): __a : List[Any] = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE ).text , 'html.parser' ) __a : Union[str, Any] = soup.findAll('h1' ) __a : int = soup.findAll('div' , {'class': 'maincounter-number'} ) keys += soup.findAll('span' , {'class': 'panel-title'} ) values += soup.findAll('div' , {'class': 'number-table-main'} ) return {key.text.strip(): value.text.strip() for key, value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
27
0
'''simple docstring''' from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( """The RoBERTa Model transformer with early exiting (DeeRoBERTa). """ , lowercase , ) class lowercase__ ( lowercase ): lowercase__ = RobertaConfig lowercase__ = """roberta""" def __init__( self : str ,lowerCamelCase__ : Any ): '''simple docstring''' super().__init__(lowerCamelCase__ ) _UpperCamelCase : List[str] = RobertaEmbeddings(lowerCamelCase__ ) self.init_weights() @add_start_docstrings( """RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. """ , lowercase , ) class lowercase__ ( lowercase ): lowercase__ = RobertaConfig lowercase__ = """roberta""" def __init__( self : Optional[Any] ,lowerCamelCase__ : Any ): '''simple docstring''' super().__init__(lowerCamelCase__ ) _UpperCamelCase : Any = config.num_labels _UpperCamelCase : List[str] = config.num_hidden_layers _UpperCamelCase : int = DeeRobertaModel(lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = nn.Dropout(config.hidden_dropout_prob ) _UpperCamelCase : Optional[Any] = nn.Linear(config.hidden_size ,self.config.num_labels ) @add_start_docstrings_to_model_forward(lowerCamelCase__ ) def UpperCamelCase_ ( self : Union[str, Any] ,lowerCamelCase__ : List[Any]=None ,lowerCamelCase__ : Optional[int]=None ,lowerCamelCase__ : Tuple=None ,lowerCamelCase__ : Optional[int]=None ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : Optional[Any]=None ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : Any=-1 ,lowerCamelCase__ : str=False ,): '''simple docstring''' _UpperCamelCase : Any = self.num_layers try: _UpperCamelCase : Tuple = self.roberta( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,position_ids=lowerCamelCase__ ,head_mask=lowerCamelCase__ ,inputs_embeds=lowerCamelCase__ ,) _UpperCamelCase : Tuple = outputs[1] _UpperCamelCase : Optional[int] = self.dropout(lowerCamelCase__ ) _UpperCamelCase : List[str] = self.classifier(lowerCamelCase__ ) _UpperCamelCase : Tuple = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _UpperCamelCase : Optional[int] = e.message _UpperCamelCase : List[str] = e.exit_layer _UpperCamelCase : Optional[Any] = outputs[0] if not self.training: _UpperCamelCase : int = entropy(lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = [] _UpperCamelCase : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression _UpperCamelCase : Union[str, Any] = MSELoss() _UpperCamelCase : Tuple = loss_fct(logits.view(-1 ) ,labels.view(-1 ) ) else: _UpperCamelCase : int = CrossEntropyLoss() _UpperCamelCase : Dict = loss_fct(logits.view(-1 ,self.num_labels ) ,labels.view(-1 ) ) # work with highway exits _UpperCamelCase : List[Any] = [] for highway_exit in outputs[-1]: _UpperCamelCase : List[Any] = highway_exit[0] if not self.training: highway_logits_all.append(lowerCamelCase__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _UpperCamelCase : List[str] = MSELoss() _UpperCamelCase : Union[str, Any] = loss_fct(highway_logits.view(-1 ) ,labels.view(-1 ) ) else: _UpperCamelCase : Optional[Any] = CrossEntropyLoss() _UpperCamelCase : str = loss_fct(highway_logits.view(-1 ,self.num_labels ) ,labels.view(-1 ) ) highway_losses.append(lowerCamelCase__ ) if train_highway: _UpperCamelCase : str = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _UpperCamelCase : Union[str, Any] = (loss,) + outputs if not self.training: _UpperCamelCase : int = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _UpperCamelCase : Any = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
83
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__a , 'embed_dim' ) ) self.parent.assertTrue(hasattr(__a , 'num_heads' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=64 , __a=3 , __a=[16, 48, 96] , __a=[1, 3, 6] , __a=[1, 2, 10] , __a=[7, 3, 3] , __a=[4, 2, 2] , __a=[2, 1, 1] , __a=[2, 2, 2] , __a=[False, False, True] , __a=[0.0, 0.0, 0.0] , __a=0.02 , __a=1E-1_2 , __a=True , __a=True , __a=2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : Optional[int] = image_size __a : List[str] = patch_sizes __a : str = patch_stride __a : Any = patch_padding __a : Dict = is_training __a : Union[str, Any] = use_labels __a : Dict = num_labels __a : List[Any] = num_channels __a : Any = embed_dim __a : int = num_heads __a : Optional[int] = stride_kv __a : Dict = depth __a : List[str] = cls_token __a : List[Any] = attention_drop_rate __a : Tuple = initializer_range __a : int = layer_norm_eps def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Dict = None if self.use_labels: # create a random int32 tensor of given shape __a : str = ids_tensor([self.batch_size] , self.num_labels ) __a : str = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = TFCvtModel(config=__a ) __a : Dict = model(__a , training=__a ) __a : Any = (self.image_size, self.image_size) __a , __a : Dict = image_size[0], image_size[1] for i in range(len(self.depth ) ): __a : Tuple = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) __a : str = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : List[Any] = self.num_labels __a : Optional[int] = TFCvtForImageClassification(__a ) __a : Dict = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () A_ = ( {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification} if is_tf_available() else {} ) A_ = False A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtModelTester(self ) __a : List[Any] = TFCvtConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason='Cvt does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = tf.keras.mixed_precision.Policy('mixed_float16' ) tf.keras.mixed_precision.set_global_policy(__a ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('float32' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : List[str] = model_class(__a ) __a : Union[str, Any] = model(**self._prepare_for_class(__a , __a ) ) __a : Any = outputs.hidden_states __a : Union[str, Any] = len(self.model_tester.depth ) self.assertEqual(len(__a ) , __a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[str] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[Any] = TFCvtModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __a : Tuple = self.default_image_processor __a : Any = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ) # forward pass __a : Any = model(**__a ) # verify the logits __a : Any = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __a : Optional[Any] = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __a , atol=1E-4 ) )
27
0
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( A__ , unittest.TestCase ): UpperCAmelCase_ :Union[str, Any] = CTRLTokenizer UpperCAmelCase_ :Dict = False UpperCAmelCase_ :List[Any] = False def __lowerCAmelCase ( self ) -> Union[str, Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase_ :Optional[int] = ["""adapt""", """re@@""", """a@@""", """apt""", """c@@""", """t""", """<unk>"""] lowerCAmelCase_ :List[Any] = dict(zip(__A , range(len(__A ) ) ) ) lowerCAmelCase_ :int = ["""#version: 0.2""", """a p""", """ap t</w>""", """r e""", """a d""", """ad apt</w>""", """"""] lowerCAmelCase_ :Optional[Any] = {"""unk_token""": """<unk>"""} lowerCAmelCase_ :int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCAmelCase_ :Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__A ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__A ) ) def __lowerCAmelCase ( self , **__A ) -> Dict: kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **__A ) def __lowerCAmelCase ( self , __A ) -> str: lowerCAmelCase_ :Dict = """adapt react readapt apt""" lowerCAmelCase_ :Union[str, Any] = """adapt react readapt apt""" return input_text, output_text def __lowerCAmelCase ( self ) -> Optional[int]: lowerCAmelCase_ :List[Any] = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCAmelCase_ :List[str] = """adapt react readapt apt""" lowerCAmelCase_ :Any = """adapt re@@ a@@ c@@ t re@@ adapt apt""".split() lowerCAmelCase_ :List[Any] = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) lowerCAmelCase_ :Tuple = tokens + [tokenizer.unk_token] lowerCAmelCase_ :Dict = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A )
84
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __lowercase : Union[str, Any] = logging.get_logger(__name__) __lowercase : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } __lowercase : Optional[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): for attribute in key.split('.' ): __a : Any = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: __a : Any = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __a : Tuple = value elif weight_type == "weight_g": __a : str = value elif weight_type == "weight_v": __a : Optional[Any] = value elif weight_type == "bias": __a : Union[str, Any] = value else: __a : List[Any] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : int = [] __a : List[str] = fairseq_model.state_dict() __a : Tuple = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight __a : int = None for name, value in fairseq_dict.items(): __a : List[str] = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == 'group' , ) __a : List[str] = True elif name.split('.' )[0] == "proj": __a : Tuple = fairseq_model.proj __a : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __a : List[Any] = True if "*" in mapped_key: __a : str = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2] __a : int = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: __a : List[Any] = 'weight_g' elif "weight_v" in name: __a : List[Any] = 'weight_v' elif "bias" in name: __a : Optional[Any] = 'bias' elif "weight" in name: __a : Tuple = 'weight' else: __a : Optional[Any] = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : List[str] = full_name.split('conv_layers.' )[-1] __a : Any = name.split('.' ) __a : List[str] = int(items[0] ) __a : List[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __a : List[str] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __a : str = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) __a : Tuple = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __a : List[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a , __a : List[str] = emb.weight.shape __a : str = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) __a : Optional[int] = emb.weight.data return lin_layer def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any ): with open(_SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' ) as f: __a : Union[str, Any] = f.readlines() __a : Tuple = [line.split(' ' )[0] for line in lines] __a : int = len(_SCREAMING_SNAKE_CASE ) __a : List[Any] = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(_SCREAMING_SNAKE_CASE , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int] , ): __a : Optional[int] = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : Any = SpeechaTextaConfig.from_pretrained( _SCREAMING_SNAKE_CASE , vocab_size=_SCREAMING_SNAKE_CASE , decoder_layers=_SCREAMING_SNAKE_CASE , do_stable_layer_norm=_SCREAMING_SNAKE_CASE ) __a : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) __a , __a , __a : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) __a : Optional[int] = model[0].eval() # set weights for wav2vec2 encoder __a : Tuple = WavaVecaModel(_SCREAMING_SNAKE_CASE ) __a : int = recursively_load_weights_wavaveca(model.encoder , _SCREAMING_SNAKE_CASE ) __a : Dict = SpeechaTextaForCausalLM(_SCREAMING_SNAKE_CASE ) __a , __a : Optional[int] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_SCREAMING_SNAKE_CASE ) # set output linear layer unexpected_keys.remove('embed_out' ) __a : Optional[Any] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) __a : Tuple = SpeechEncoderDecoderModel(encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) __a : int = False # add projection layer __a : str = nn.Parameter(projection_layer.weight ) __a : Any = nn.Parameter(projection_layer.bias ) __a : str = create_vocab_dict(_SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) , 'w' ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = SpeechaTextaTokenizer(os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) ) tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = hf_wavavec.config.to_dict() __a : Tuple = tokenizer.pad_token_id __a : Optional[int] = tokenizer.bos_token_id __a : Union[str, Any] = tokenizer.eos_token_id __a : Tuple = 'speech_to_text_2' __a : Tuple = 'wav2vec2' __a : List[str] = SpeechEncoderDecoderConfig.from_dict(_SCREAMING_SNAKE_CASE ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-large-lv60', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/s2t-small-mustc-en-fr-st', type=str, help='Path to hf decoder s2t checkpoint config', ) parser.add_argument('--vocab_size', default=1_02_24, type=int, help='Vocab size of decoder') parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers') __lowercase : Tuple = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
27
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : Any = { "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"], "tokenization_roc_bert": ["RoCBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys _SCREAMING_SNAKE_CASE : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
'''simple docstring''' # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int ): with open(_SCREAMING_SNAKE_CASE , 'r' ) as fh: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_EX ) try: print(*_SCREAMING_SNAKE_CASE ) finally: fcntl.flock(_SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) __lowercase : Dict = int(os.environ['LOCAL_RANK']) torch.cuda.set_device(local_rank) __lowercase : Tuple = torch.device('cuda', local_rank) __lowercase : Optional[int] = socket.gethostname() __lowercase : List[str] = f'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group('nccl') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __lowercase : str = dist.get_rank() __lowercase : Union[str, Any] = dist.get_world_size() printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(f'''{gpu} is broken''') raise
27
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """google/mobilenet_v2_1.4_224""": """https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json""", """google/mobilenet_v2_1.0_224""": """https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json""", """google/mobilenet_v2_0.75_160""": """https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json""", """google/mobilenet_v2_0.35_96""": """https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json""", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class A__ ( _lowerCamelCase): A_ : int = 'mobilenet_v2' def __init__( self , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=2_24 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu6" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.8 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=0.001 , _SCREAMING_SNAKE_CASE=2_55 , **_SCREAMING_SNAKE_CASE , ): super().__init__(**_SCREAMING_SNAKE_CASE ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) __lowerCAmelCase : Union[str, Any] = num_channels __lowerCAmelCase : Optional[Any] = image_size __lowerCAmelCase : List[str] = depth_multiplier __lowerCAmelCase : int = depth_divisible_by __lowerCAmelCase : Union[str, Any] = min_depth __lowerCAmelCase : int = expand_ratio __lowerCAmelCase : Optional[Any] = output_stride __lowerCAmelCase : List[str] = first_layer_is_expansion __lowerCAmelCase : int = finegrained_output __lowerCAmelCase : Dict = hidden_act __lowerCAmelCase : Optional[Any] = tf_padding __lowerCAmelCase : Optional[int] = classifier_dropout_prob __lowerCAmelCase : Tuple = initializer_range __lowerCAmelCase : Tuple = layer_norm_eps __lowerCAmelCase : List[Any] = semantic_loss_ignore_index class A__ ( _lowerCamelCase): A_ : List[str] = version.parse('1.11') @property def __lowerCamelCase ( self ): return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def __lowerCamelCase ( self ): if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def __lowerCamelCase ( self ): return 1E-4
86
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase : str = { '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: __lowercase : str = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] __lowercase : Tuple = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] __lowercase : Dict = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): __lowercase : Optional[Any] = [ '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 __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class snake_case_ ( __A ,unittest.TestCase ): __A : Any = PriorTransformer __A : Union[str, Any] = "hidden_states" @property def __UpperCamelCase ( self : Dict ) -> str: lowercase__ : Optional[Any] = 4 lowercase__ : Any = 8 lowercase__ : str = 7 lowercase__ : Dict = floats_tensor((batch_size, embedding_dim) ).to(lowercase_ ) lowercase__ : List[str] = floats_tensor((batch_size, embedding_dim) ).to(lowercase_ ) lowercase__ : Dict = floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(lowercase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def __UpperCamelCase ( self : Dict , lowercase_ : Optional[int]=0 ) -> int: torch.manual_seed(lowercase_ ) lowercase__ : Tuple = 4 lowercase__ : Optional[int] = 8 lowercase__ : int = 7 lowercase__ : Union[str, Any] = torch.randn((batch_size, embedding_dim) ).to(lowercase_ ) lowercase__ : Any = torch.randn((batch_size, embedding_dim) ).to(lowercase_ ) lowercase__ : List[Any] = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(lowercase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def __UpperCamelCase ( self : List[str] ) -> Optional[int]: return (4, 8) @property def __UpperCamelCase ( self : int ) -> int: return (4, 8) def __UpperCamelCase ( self : List[Any] ) -> Optional[Any]: lowercase__ : Union[str, Any] = { "num_attention_heads": 2, "attention_head_dim": 4, "num_layers": 2, "embedding_dim": 8, "num_embeddings": 7, "additional_embeddings": 4, } lowercase__ : Tuple = self.dummy_input return init_dict, inputs_dict def __UpperCamelCase ( self : Optional[int] ) -> List[str]: lowercase__ , lowercase__ : Any = PriorTransformer.from_pretrained( "hf-internal-testing/prior-dummy" , output_loading_info=lowercase_ ) self.assertIsNotNone(lowercase_ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase_ ) lowercase__ : Dict = model(**self.dummy_input )[0] assert hidden_states is not None, "Make sure output is not None" def __UpperCamelCase ( self : Optional[Any] ) -> Union[str, Any]: lowercase__ , lowercase__ : str = self.prepare_init_args_and_inputs_for_common() lowercase__ : Any = self.model_class(**lowercase_ ) lowercase__ : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Optional[int] = [*signature.parameters.keys()] lowercase__ : Optional[Any] = ["hidden_states", "timestep"] self.assertListEqual(arg_names[:2] , lowercase_ ) def __UpperCamelCase ( self : Optional[int] ) -> Optional[int]: lowercase__ : str = PriorTransformer.from_pretrained("hf-internal-testing/prior-dummy" ) lowercase__ : Tuple = model.to(lowercase_ ) if hasattr(lowercase_ , "set_default_attn_processor" ): model.set_default_attn_processor() lowercase__ : Tuple = self.get_dummy_seed_input() with torch.no_grad(): lowercase__ : Union[str, Any] = model(**lowercase_ )[0] lowercase__ : int = output[0, :5].flatten().cpu() print(lowercase_ ) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. lowercase__ : Dict = torch.tensor([-1.34_36, -0.28_70, 0.75_38, 0.43_68, -0.02_39] ) self.assertTrue(torch_all_close(lowercase_ , lowercase_ , rtol=1E-2 ) ) @slow class snake_case_ ( unittest.TestCase ): def __UpperCamelCase ( self : Optional[Any] , lowercase_ : Any=1 , lowercase_ : Any=7_68 , lowercase_ : Any=77 , lowercase_ : Tuple=0 ) -> int: torch.manual_seed(lowercase_ ) lowercase__ : int = batch_size lowercase__ : Any = embedding_dim lowercase__ : Dict = num_embeddings lowercase__ : str = torch.randn((batch_size, embedding_dim) ).to(lowercase_ ) lowercase__ : Optional[int] = torch.randn((batch_size, embedding_dim) ).to(lowercase_ ) lowercase__ : str = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(lowercase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def __UpperCamelCase ( self : Any ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.58_61, 0.12_83, -0.09_31, 0.08_82, 0.44_76, 0.13_29, -0.04_98, 0.06_40]], [37, [-0.49_13, 0.01_10, -0.04_83, 0.05_41, 0.49_54, -0.01_70, 0.03_54, 0.16_51]], # fmt: on ] ) def __UpperCamelCase ( self : Dict , lowercase_ : Dict , lowercase_ : Optional[int] ) -> List[Any]: lowercase__ : Tuple = PriorTransformer.from_pretrained("kandinsky-community/kandinsky-2-1-prior" , subfolder="prior" ) model.to(lowercase_ ) lowercase__ : Any = self.get_dummy_seed_input(seed=lowercase_ ) with torch.no_grad(): lowercase__ : int = model(**lowercase_ )[0] assert list(sample.shape ) == [1, 7_68] lowercase__ : List[Any] = sample[0, :8].flatten().cpu() print(lowercase_ ) lowercase__ : List[Any] = torch.tensor(lowercase_ ) assert torch_all_close(lowercase_ , lowercase_ , atol=1E-3 )
87
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration __lowercase : Tuple = pytest.mark.integration __lowercase : Optional[int] = {'comet'} __lowercase : List[str] = importlib.util.find_spec('fairseq') is not None __lowercase : str = {'code_eval'} __lowercase : List[Any] = os.name == 'nt' __lowercase : Optional[Any] = {'bertscore', 'frugalscore', 'perplexity'} __lowercase : Optional[Any] = importlib.util.find_spec('transformers') is not None def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : int , _SCREAMING_SNAKE_CASE : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def lowerCamelCase (): __a : List[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) @local class __UpperCamelCase ( parameterized.TestCase ): A_ = {} A_ = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = '[...]' __a : Tuple = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) __a : Optional[Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=__a ) # check parameters __a : Dict = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__a , metric_module.__name__ ): with self.use_local_metrics(): try: __a : str = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = '[...]' __a : Optional[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a ) ).module_path ) # run doctest with self.use_local_metrics(): __a : List[Any] = doctest.testmod(__a , verbose=__a , raise_on_error=__a ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__a ): yield else: yield @contextmanager def __UpperCAmelCase ( self ): '''simple docstring''' def load_local_metric(__a , *__a , **__a ): return load_metric(os.path.join('metrics' , __a ) , *__a , **__a ) with patch('datasets.load_metric' ) as mock_load_metric: __a : Dict = load_local_metric yield @classmethod def __UpperCAmelCase ( cls , __a ): '''simple docstring''' def wrapper(__a ): __a : Optional[Any] = contextmanager(__a ) __a : str = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self , __a ): '''simple docstring''' assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: __a : Dict = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): import torch def bert_cos_score_idf(_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , *_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Optional[int] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: __a : str = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): def load_from_checkpoint(_SCREAMING_SNAKE_CASE : Optional[int] ): class __UpperCamelCase : def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' assert len(__a ) == 2 __a : Dict = [0.19, 0.92] return scores, sum(__a ) / len(__a ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: __a : str = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: __a : int = load_from_checkpoint yield def lowerCamelCase (): __a : Optional[Any] = load_metric(os.path.join('metrics' , 'seqeval' ) ) __a : List[str] = 'ERROR' __a : List[str] = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): metric.compute(predictions=[] , references=[] , scheme=_SCREAMING_SNAKE_CASE )
27
0
from queue import PriorityQueue from typing import Any import numpy as np def a__ ( A_, A_, A_, A_, A_, A_, A_, A_, A_, ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue __magic_name__ = cst_fwd.get(A_, np.inf ) __magic_name__ = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __magic_name__ = new_cost_f __magic_name__ = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __magic_name__ = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = -1 __magic_name__ = set() __magic_name__ = set() __magic_name__ = {source: 0} __magic_name__ = {destination: 0} __magic_name__ = {source: None} __magic_name__ = {destination: None} __magic_name__ = PriorityQueue() __magic_name__ = PriorityQueue() __magic_name__ = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __magic_name__ , __magic_name__ = queue_forward.get() visited_forward.add(A_ ) __magic_name__ , __magic_name__ = queue_backward.get() visited_backward.add(A_ ) __magic_name__ = pass_and_relaxation( A_, A_, A_, A_, A_, A_, A_, A_, A_, ) __magic_name__ = pass_and_relaxation( A_, A_, A_, A_, A_, A_, A_, A_, A_, ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __magic_name__ = shortest_distance return shortest_path_distance __lowerCAmelCase : Optional[Any] = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } __lowerCAmelCase : Optional[Any] = { 'B': [['E', 1]], 'C': [['B', 1]], 'D': [['C', 1]], 'F': [['D', 1], ['G', 1]], 'E': [[None, np.inf]], 'G': [['E', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
88
'''simple docstring''' import re import string import numpy as np import datasets __lowercase : Tuple = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' __lowercase : List[str] = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' __lowercase : Any = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def __UpperCAmelCase ( 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' ), } ) , reference_urls=[] , ) def __UpperCAmelCase ( self , __a , __a , __a=None , __a=False , __a=False , __a=False , ): '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: __a : Tuple = np.array([re.sub(__a , '' , __a ) for x in predictions] ) __a : List[Any] = np.array([re.sub(__a , '' , __a ) for x in references] ) else: __a : int = np.asarray(__a ) __a : str = np.asarray(__a ) if ignore_case: __a : Dict = np.char.lower(__a ) __a : List[str] = np.char.lower(__a ) if ignore_punctuation: __a : Dict = string.punctuation.maketrans('' , '' , string.punctuation ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Dict = np.char.translate(__a , table=__a ) if ignore_numbers: __a : Optional[int] = string.digits.maketrans('' , '' , string.digits ) __a : Tuple = np.char.translate(__a , table=__a ) __a : Optional[int] = np.char.translate(__a , table=__a ) __a : Any = predictions == references return {"exact_match": np.mean(__a ) * 100}
27
0
'''simple docstring''' # limitations under the License. # 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 .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( '''pipelines_utils''', '''0.22.0''', '''Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.''', standard_warn=False, stacklevel=3, )
89
'''simple docstring''' import os import sys __lowercase : List[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowercase : int = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[str] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoConfig.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoTokenizer.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : str , **_SCREAMING_SNAKE_CASE : Any ): return AutoTokenizer.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModel.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Union[str, Any] ): return AutoModel.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : List[Any] , **_SCREAMING_SNAKE_CASE : Optional[int] ): return AutoModelForCausalLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Union[str, Any] , **_SCREAMING_SNAKE_CASE : List[Any] ): return AutoModelForMaskedLM.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Optional[Any] , **_SCREAMING_SNAKE_CASE : Any ): return AutoModelForSequenceClassification.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Any , **_SCREAMING_SNAKE_CASE : List[str] ): return AutoModelForQuestionAnswering.from_pretrained(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
27
0
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__)
90
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = inspect.getfile(accelerate.test_utils ) __a : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __a : Union[str, Any] = test_metrics @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def __UpperCAmelCase ( self ): '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def __UpperCAmelCase ( self ): '''simple docstring''' self.test_metrics.main() @require_multi_gpu def __UpperCAmelCase ( self ): '''simple docstring''' print(f"""Found {torch.cuda.device_count()} devices.""" ) __a : List[Any] = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() )
27
0
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : List[str]=13 , lowercase_ : Union[str, Any]=30 , lowercase_ : List[Any]=2 , lowercase_ : List[str]=3 , lowercase_ : Union[str, Any]=True , lowercase_ : int=True , lowercase_ : Tuple=32 , lowercase_ : Tuple=5 , lowercase_ : Union[str, Any]=4 , lowercase_ : Dict=37 , lowercase_ : Optional[int]="gelu" , lowercase_ : str=0.1 , lowercase_ : List[str]=0.1 , lowercase_ : List[str]=10 , lowercase_ : Dict=0.02 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : List[str] = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : Optional[int] = is_training SCREAMING_SNAKE_CASE_ : Any = use_labels SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : int = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Dict = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE_ : Any = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE_ : Tuple = num_patches + 1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase_ , initializer_range=self.initializer_range , ) return config, pixel_values def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[Any] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = FlaxViTModel(config=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = model(lowercase_) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE_ : str = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ : Tuple = (self.patch_size, self.patch_size) SCREAMING_SNAKE_CASE_ : int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size)) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : Any , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.type_sequence_label_size SCREAMING_SNAKE_CASE_ : Dict = FlaxViTForImageClassification(config=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images SCREAMING_SNAKE_CASE_ : int = 1 SCREAMING_SNAKE_CASE_ : List[str] = FlaxViTForImageClassification(lowercase_) SCREAMING_SNAKE_CASE_ : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Any = model(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxViTModelTester(self) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : str = inspect.signature(model.__call__) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Tuple = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) @jax.jit def model_jitted(lowercase_ : int , **lowercase_ : Optional[Any]): return model(pixel_values=lowercase_ , **lowercase_) with self.subTest('''JIT Enabled'''): SCREAMING_SNAKE_CASE_ : Tuple = model_jitted(**lowercase_).to_tuple() with self.subTest('''JIT Disabled'''): with jax.disable_jit(): SCREAMING_SNAKE_CASE_ : Optional[int] = model_jitted(**lowercase_).to_tuple() self.assertEqual(len(lowercase_) , len(lowercase_)) for jitted_output, output in zip(lowercase_ , lowercase_): self.assertEqual(jitted_output.shape , output.shape) @slow def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE_ : List[Any] = model_class_name.from_pretrained('''google/vit-base-patch16-224''') SCREAMING_SNAKE_CASE_ : List[str] = model(np.ones((1, 3, 224, 224))) self.assertIsNotNone(lowercase_)
91
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): __a : Optional[Any] = tmp_path / 'file.csv' __a : Union[str, Any] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : str = tmp_path / 'malformed_file.csv' __a : int = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = tmp_path / 'csv_with_image.csv' __a : Dict = textwrap.dedent( F"""\ image {image_file} """ ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Union[str, Any] = tmp_path / 'csv_with_label.csv' __a : Any = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Dict = tmp_path / 'csv_with_int_list.csv' __a : Tuple = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): __a : int = Csv() __a : str = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_SCREAMING_SNAKE_CASE , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(_SCREAMING_SNAKE_CASE ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1] __a : Tuple = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) __a : Any = csv._generate_tables([[csv_file_with_image]] ) __a : int = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() __a : Any = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: __a : Tuple = f.read().splitlines()[1:] __a : Optional[int] = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) __a : List[str] = csv._generate_tables([[csv_file_with_label]] ) __a : Dict = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() __a : int = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(_SCREAMING_SNAKE_CASE ) for label in labels] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda _SCREAMING_SNAKE_CASE : [int(_SCREAMING_SNAKE_CASE ) for i in x.split()]} ) __a : Any = csv._generate_tables([[csv_file_with_int_list]] ) __a : Any = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) __a : Tuple = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
27
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @dataclass class a__ ( snake_case__ ): _a : List[str] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_A ): """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCAmelCase = deprecated_arg[3:] __lowerCAmelCase = not kwargs.pop(_A ) logger.warning( f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" f""" {positive_arg}={kwargs[positive_arg]}""" ) __lowerCAmelCase = kwargs.pop("tpu_name" , self.tpu_name ) __lowerCAmelCase = kwargs.pop("device_idx" , self.device_idx ) __lowerCAmelCase = kwargs.pop("eager_mode" , self.eager_mode ) __lowerCAmelCase = kwargs.pop("use_xla" , self.use_xla ) super().__init__(**_A ) _a : str = field( default=snake_case__ , metadata={"""help""": """Name of TPU"""} , ) _a : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _a : bool = field(default=snake_case__ , metadata={"""help""": """Benchmark models in eager model."""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) __lowerCAmelCase = None if self.tpu: try: if self.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __lowerCAmelCase = None return tpu @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __lowerCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" ) __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , "GPU" ) # disable GPU __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}""" ) return strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_tpu is not None @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.n_gpu > 0
92
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Union[str, Any] = { 'configuration_blenderbot': [ 'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotConfig', 'BlenderbotOnnxConfig', ], 'tokenization_blenderbot': ['BlenderbotTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ['BlenderbotTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = [ 'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotForCausalLM', 'BlenderbotForConditionalGeneration', 'BlenderbotModel', 'BlenderbotPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ 'TFBlenderbotForConditionalGeneration', 'TFBlenderbotModel', 'TFBlenderbotPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Dict = [ 'FlaxBlenderbotForConditionalGeneration', 'FlaxBlenderbotModel', 'FlaxBlenderbotPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
'''simple docstring''' from __future__ import annotations from cmath import sqrt def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if a == 0: raise ValueError('''Coefficient \'a\' must not be zero.''' ) lowercase_ : List[Any] = b * b - 4 * a * c lowercase_ : Dict = (-b + sqrt(__SCREAMING_SNAKE_CASE )) / (2 * a) lowercase_ : Tuple = (-b - sqrt(__SCREAMING_SNAKE_CASE )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = quadratic_roots(a=5 , b=6 , c=1 ) print(F'''The solutions are: {solutiona} and {solutiona}''' ) if __name__ == "__main__": main()
93
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase : def __init__( self , __a , __a=2 , __a=3 , __a=4 , __a=2 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=36 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=6 , __a=6 , __a=3 , __a=4 , __a=None , __a=1000 , ): '''simple docstring''' __a : Optional[Any] = parent __a : int = batch_size __a : Any = num_channels __a : Optional[int] = image_size __a : Dict = patch_size __a : int = is_training __a : Union[str, Any] = use_input_mask __a : Optional[int] = use_token_type_ids __a : Dict = use_labels __a : str = vocab_size __a : List[Any] = hidden_size __a : Union[str, Any] = num_hidden_layers __a : str = num_attention_heads __a : Union[str, Any] = intermediate_size __a : Any = hidden_act __a : List[str] = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : List[Any] = max_position_embeddings __a : Tuple = type_vocab_size __a : Any = type_sequence_label_size __a : Optional[int] = initializer_range __a : Any = coordinate_size __a : List[Any] = shape_size __a : Optional[int] = num_labels __a : Dict = num_choices __a : Union[str, Any] = scope __a : Union[str, Any] = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __a : Optional[int] = text_seq_length __a : Any = (image_size // patch_size) ** 2 + 1 __a : Dict = self.text_seq_length + self.image_seq_length def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __a : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __a : Any = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a : List[Any] = bbox[i, j, 3] __a : Tuple = bbox[i, j, 1] __a : str = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __a : int = bbox[i, j, 2] __a : Dict = bbox[i, j, 0] __a : int = tmp_coordinate __a : Optional[int] = tf.constant(__a ) __a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_input_mask: __a : Optional[Any] = random_attention_mask([self.batch_size, self.text_seq_length] ) __a : str = None if self.use_token_type_ids: __a : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __a : Optional[Any] = None __a : Optional[int] = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __a : int = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = TFLayoutLMvaModel(config=__a ) # text + image __a : List[Any] = model(__a , pixel_values=__a , training=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , training=__a , ) __a : Optional[int] = model(__a , bbox=__a , pixel_values=__a , training=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __a : Any = model(__a , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __a : str = model({'pixel_values': pixel_values} , training=__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = TFLayoutLMvaForSequenceClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : str = self.num_labels __a : Optional[Any] = TFLayoutLMvaForTokenClassification(config=__a ) __a : List[str] = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , labels=__a , training=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[Any] = 2 __a : Any = TFLayoutLMvaForQuestionAnswering(config=__a ) __a : Any = model( __a , bbox=__a , pixel_values=__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , training=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a) , (__a)) : Dict = config_and_inputs __a : Any = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) A_ = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) A_ = False A_ = False A_ = False def __UpperCAmelCase ( self , __a , __a , __a , __a , __a ): '''simple docstring''' return True def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : str = copy.deepcopy(__a ) if model_class in get_values(__a ): __a : str = { k: tf.tile(tf.expand_dims(__a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(__a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__a ): __a : Optional[int] = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : int = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __a : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__a ): __a : Union[str, Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = TFLayoutLMvaModelTester(self ) __a : Optional[int] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) if getattr(__a , 'hf_compute_loss' , __a ): # The number of elements in the loss should be the same as the number of elements in the label __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=__a )[0] ] __a : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : Dict = prepared_for_class.pop('input_ids' ) __a : Tuple = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __a : int = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __a : Union[str, Any] = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __a : List[Any] = -100 __a : List[str] = tf.convert_to_tensor(__a ) __a : Any = model(__a , **__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __a : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) __a : str = model(__a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __a : Tuple = self._prepare_for_class(inputs_dict.copy() , __a , return_labels=__a ) # Get keys that were added with the _prepare_for_class function __a : Dict = prepared_for_class.keys() - inputs_dict.keys() __a : Any = inspect.signature(model.call ).parameters __a : str = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __a : List[Any] = {0: 'input_ids'} for label_key in label_keys: __a : List[Any] = signature_names.index(__a ) __a : Union[str, Any] = label_key __a : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __a : Union[str, Any] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __a : Optional[Any] = prepared_for_class[value] __a : str = tuple(__a ) # Send to model __a : Tuple = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a : Any = type self.model_tester.create_and_check_model(__a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( __a , __a , __a , __a , __a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( __a , __a , __a , __a , __a , __a , __a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = TFLayoutLMvaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__a ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __a : Tuple = self.default_image_processor __a : List[Any] = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ).pixel_values __a : Union[str, Any] = tf.constant([[1, 2]] ) __a : Optional[Any] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __a : Tuple = model(input_ids=__a , bbox=__a , pixel_values=__a , training=__a ) # verify the logits __a : List[Any] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , __a ) __a : Optional[Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , __a , atol=1E-4 ) )
27
0
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def __lowerCamelCase ( UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] ): """simple docstring""" for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), F'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), F'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})''' def __lowerCamelCase ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any]=True ): """simple docstring""" model.train() a :str = model(UpperCAmelCase_ ) a :List[str] = F.mse_loss(UpperCAmelCase_ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(UpperCAmelCase_ ) def __lowerCamelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : int=False ): """simple docstring""" set_seed(42 ) a :List[Any] = RegressionModel() a :Any = deepcopy(UpperCAmelCase_ ) a :Tuple = RegressionDataset(length=80 ) a :Tuple = DataLoader(UpperCAmelCase_ , batch_size=16 ) model.to(accelerator.device ) if sched: a :str = AdamW(params=model.parameters() , lr=1E-3 ) a :str = AdamW(params=ddp_model.parameters() , lr=1E-3 ) a :List[str] = LambdaLR(UpperCAmelCase_ , lr_lambda=lambda UpperCAmelCase_ : epoch**0.65 ) a :List[str] = LambdaLR(UpperCAmelCase_ , lr_lambda=lambda UpperCAmelCase_ : epoch**0.65 ) # Make a copy of `model` if sched: a , a , a , a :List[Any] = accelerator.prepare(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) else: a , a :str = accelerator.prepare(UpperCAmelCase_ , UpperCAmelCase_ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def __lowerCamelCase ( UpperCAmelCase_ : Union[str, Any] ): """simple docstring""" a , a , a :str = get_training_setup(UpperCAmelCase_ ) # Use a single batch a , a :Dict = next(iter(UpperCAmelCase_ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model a , a :int = accelerator.gather((ddp_input, ddp_target) ) a , a :Union[str, Any] = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCAmelCase_ ): step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) else: # Sync grads step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), F'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) a :Union[str, Any] = ddp_input[torch.randperm(len(UpperCAmelCase_ ) )] def __lowerCamelCase ( UpperCAmelCase_ : Union[str, Any] ): """simple docstring""" a , a , a :List[str] = get_training_setup(UpperCAmelCase_ ) # Use a single batch a , a :List[str] = next(iter(UpperCAmelCase_ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model a , a :List[Any] = accelerator.gather((ddp_input, ddp_target) ) a , a :Union[str, Any] = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCAmelCase_ ): step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) else: # Sync grads step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) a :Any = ddp_input[torch.randperm(len(UpperCAmelCase_ ) )] def __lowerCamelCase ( UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : int=False ): """simple docstring""" a :Optional[int] = Accelerator( split_batches=UpperCAmelCase_ , dispatch_batches=UpperCAmelCase_ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly a , a , a :List[str] = get_training_setup(UpperCAmelCase_ ) for iteration, batch in enumerate(UpperCAmelCase_ ): a , a :List[Any] = batch.values() # Gather the distributed inputs and targs for the base model a , a :List[str] = accelerator.gather((ddp_input, ddp_target) ) a , a :List[str] = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(UpperCAmelCase_ ): step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(UpperCAmelCase_ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) a :List[str] = ddp_input[torch.randperm(len(UpperCAmelCase_ ) )] GradientState._reset_state() def __lowerCamelCase ( UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Optional[int]=False ): """simple docstring""" a :Optional[Any] = Accelerator( split_batches=UpperCAmelCase_ , dispatch_batches=UpperCAmelCase_ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly a , a , a , a , a , a , a :Optional[Any] = get_training_setup(UpperCAmelCase_ , UpperCAmelCase_ ) for iteration, batch in enumerate(UpperCAmelCase_ ): a , a :int = batch.values() # Gather the distributed inputs and targs for the base model a , a :List[str] = accelerator.gather((ddp_input, ddp_target) ) a , a :str = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCAmelCase_ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(UpperCAmelCase_ ): step_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), F'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n''' a :Tuple = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(UpperCAmelCase_ )) if accelerator.num_processes > 1: check_model_parameters(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) GradientState._reset_state() def __lowerCamelCase ( ): """simple docstring""" a :Optional[Any] = Accelerator() a :int = RegressionDataset(length=80 ) a :List[str] = DataLoader(UpperCAmelCase_ , batch_size=16 ) a :List[Any] = RegressionDataset(length=96 ) a :Any = DataLoader(UpperCAmelCase_ , batch_size=16 ) a , a :Optional[int] = accelerator.prepare(UpperCAmelCase_ , UpperCAmelCase_ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(UpperCAmelCase_ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCAmelCase_ ) if iteration < len(UpperCAmelCase_ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(UpperCAmelCase_ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCAmelCase_ ) if batch_num < len(UpperCAmelCase_ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def __lowerCamelCase ( ): """simple docstring""" a :Optional[int] = Accelerator() a :Optional[int] = accelerator.state if state.local_process_index == 0: print('''**Test `accumulate` gradient accumulation with dataloader break**''' ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print('''**Test NOOP `no_sync` context manager**''' ) test_noop_sync(UpperCAmelCase_ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print('''**Test Distributed `no_sync` context manager**''' ) test_distributed_sync(UpperCAmelCase_ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation, ''' , F'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation(UpperCAmelCase_ , UpperCAmelCase_ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version('''<''' , '''2.0''' ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''' , '''`split_batches=False`, `dispatch_batches=False`**''' , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''' , F'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation_with_opt_and_scheduler(UpperCAmelCase_ , UpperCAmelCase_ ) def __lowerCamelCase ( UpperCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
94
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"""{test_file} instead.""" ) __a : Tuple = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __a : List[str] = components[:-1] + [test_fn.replace('.py' , '' )] __a : Optional[Any] = '.'.join(_SCREAMING_SNAKE_CASE ) return test_module_path def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = get_module_path(_SCREAMING_SNAKE_CASE ) __a : Dict = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = [] __a : List[str] = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : Any = [] __a : str = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): __a : int = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'all_model_classes' , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Tuple = test_class() if hasattr(_SCREAMING_SNAKE_CASE , 'setUp' ): test.setUp() __a : List[Any] = None if hasattr(_SCREAMING_SNAKE_CASE , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __a : List[str] = test.model_tester.__class__ return model_tester def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] ): __a : List[Any] = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [] for test_class in test_classes: __a : Any = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : str = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
27
0
def _A ( SCREAMING_SNAKE_CASE : list[int] ): """simple docstring""" if not nums: # Makes sure that the list is not empty raise ValueError("List is empty" ) a__ : List[str] =sum(SCREAMING_SNAKE_CASE ) / len(SCREAMING_SNAKE_CASE ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = StableDiffusionInpaintPipeline A_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS A_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS A_ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess A_ = frozenset([] ) def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__a , ) __a : str = PNDMScheduler(skip_prk_steps=__a ) torch.manual_seed(0 ) __a : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __a : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __a : Dict = CLIPTextModel(__a ) __a : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __a : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCAmelCase ( self , __a , __a=0 ): '''simple docstring''' __a : Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) __a : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a : Tuple = Image.fromarray(np.uinta(__a ) ).convert('RGB' ).resize((64, 64) ) __a : Tuple = Image.fromarray(np.uinta(image + 4 ) ).convert('RGB' ).resize((64, 64) ) if str(__a ).startswith('mps' ): __a : Any = torch.manual_seed(__a ) else: __a : str = torch.Generator(device=__a ).manual_seed(__a ) __a : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': init_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator __a : str = self.get_dummy_components() __a : Union[str, Any] = StableDiffusionInpaintPipeline(**__a ) __a : List[Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) __a : List[Any] = self.get_dummy_inputs(__a ) __a : Dict = sd_pipe(**__a ).images __a : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : List[Any] = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench.npy' ) __a : Optional[int] = 'stabilityai/stable-diffusion-2-inpainting' __a : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained(__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Dict = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : int = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench_fp16.npy' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : List[str] = StableDiffusionInpaintPipeline.from_pretrained( __a , torch_dtype=torch.floataa , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() __a : Union[str, Any] = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : int = torch.manual_seed(0 ) __a : Optional[Any] = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type='np' , ) __a : int = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def __UpperCAmelCase ( self ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __a : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __a : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __a : str = 'stabilityai/stable-diffusion-2-inpainting' __a : Any = PNDMScheduler.from_pretrained(__a , subfolder='scheduler' ) __a : str = StableDiffusionInpaintPipeline.from_pretrained( __a , safety_checker=__a , scheduler=__a , torch_dtype=torch.floataa , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __a : str = 'Face of a yellow cat, high resolution, sitting on a park bench' __a : Tuple = torch.manual_seed(0 ) __a : str = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , num_inference_steps=2 , output_type='np' , ) __a : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
27
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase__ = { """configuration_graphormer""": ["""GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GraphormerConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ """GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """GraphormerForGraphClassification""", """GraphormerModel""", """GraphormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
96
'''simple docstring''' import requests __lowercase : Tuple = '' # <-- Put your OpenWeatherMap appid here! __lowercase : Tuple = 'https://api.openweathermap.org/data/2.5/' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Chicago" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'weather' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Kolkata, India" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : float = 5_5.6_8 , _SCREAMING_SNAKE_CASE : float = 1_2.5_7 , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowercase : Dict = input('Enter a location:').strip() if location: pprint(current_weather(location)) else: break
27
0
'''simple docstring''' import math import sys def a ( __a ) -> int: '''simple docstring''' if number != int(__a ): raise ValueError('''the value of input must be a natural number''' ) if number < 0: raise ValueError('''the value of input must not be a negative number''' ) if number == 0: return 1 UpperCamelCase__ :str = [-1] * (number + 1) UpperCamelCase__ :Optional[int] = 0 for i in range(1 , number + 1 ): UpperCamelCase__ :List[Any] = sys.maxsize UpperCamelCase__ :int = int(math.sqrt(__a ) ) for j in range(1 , root + 1 ): UpperCamelCase__ :int = 1 + answers[i - (j**2)] UpperCamelCase__ :str = min(__a , __a ) UpperCamelCase__ :Dict = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
97
'''simple docstring''' import torch from transformers import AutoModel class __UpperCamelCase ( torch.nn.Module ): def __init__( self , __a="sayef/fsner-bert-base-uncased" ): '''simple docstring''' super(__a , self ).__init__() __a : Tuple = AutoModel.from_pretrained(__a , return_dict=__a ) __a : int = torch.nn.CosineSimilarity(3 , 1E-0_8 ) __a : Union[str, Any] = torch.nn.Softmax(dim=1 ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return self.bert(**__a ).last_hidden_state def __UpperCAmelCase ( self , __a ): '''simple docstring''' return token_embeddings.sum(2 , keepdim=__a ) def __UpperCAmelCase ( self , __a , __a , __a=1 ): '''simple docstring''' return self.softmax(T * self.cos(__a , __a ) ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : str = W_supports['sizes'].tolist() __a : Union[str, Any] = W_supports['start_token_id'].item() __a : Any = W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __a : Tuple = self.BERT(**__a ) __a : str = self.BERT(**__a ) __a : Any = None __a : Dict = None __a : Dict = W_supports['input_ids'] == start_token_id __a : Union[str, Any] = W_supports['input_ids'] == end_token_id for i, size in enumerate(__a ): if i == 0: __a : Optional[int] = 0 else: __a : Union[str, Any] = support_sizes[i - 1] __a : int = S[s : s + size][start_token_masks[s : s + size]] __a : Union[str, Any] = S[s : s + size][end_token_masks[s : s + size]] __a : Tuple = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __a : Dict = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __a : str = torch.vstack((p_starts, p_start) ) __a : str = torch.vstack((p_ends, p_end) ) else: __a : List[str] = p_start __a : int = p_end return p_starts, p_ends
27
0
"""simple docstring""" import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class snake_case ( __UpperCAmelCase ): """simple docstring""" def __get__( self : str ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[str]=None ): # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError('unreadable attribute' ) UpperCAmelCase__ = '__cached_' + self.fget.__name__ UpperCAmelCase__ = getattr(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) if cached is None: UpperCAmelCase__ = self.fget(lowerCamelCase__ ) setattr(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) return cached def a_ ( lowerCamelCase ): UpperCAmelCase__ = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f'''invalid truth value {val!r}''' ) def a_ ( lowerCamelCase ): if is_torch_fx_proxy(lowerCamelCase ): return True if is_torch_available(): import torch if isinstance(lowerCamelCase , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(lowerCamelCase , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(lowerCamelCase , (jnp.ndarray, Tracer) ): return True return isinstance(lowerCamelCase , np.ndarray ) def a_ ( lowerCamelCase ): return isinstance(lowerCamelCase , np.ndarray ) def a_ ( lowerCamelCase ): return _is_numpy(lowerCamelCase ) def a_ ( lowerCamelCase ): import torch return isinstance(lowerCamelCase , torch.Tensor ) def a_ ( lowerCamelCase ): return False if not is_torch_available() else _is_torch(lowerCamelCase ) def a_ ( lowerCamelCase ): import torch return isinstance(lowerCamelCase , torch.device ) def a_ ( lowerCamelCase ): return False if not is_torch_available() else _is_torch_device(lowerCamelCase ) def a_ ( lowerCamelCase ): import torch if isinstance(lowerCamelCase , lowerCamelCase ): if hasattr(lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = getattr(lowerCamelCase , lowerCamelCase ) else: return False return isinstance(lowerCamelCase , torch.dtype ) def a_ ( lowerCamelCase ): return False if not is_torch_available() else _is_torch_dtype(lowerCamelCase ) def a_ ( lowerCamelCase ): import tensorflow as tf return isinstance(lowerCamelCase , tf.Tensor ) def a_ ( lowerCamelCase ): return False if not is_tf_available() else _is_tensorflow(lowerCamelCase ) def a_ ( lowerCamelCase ): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(lowerCamelCase , 'is_symbolic_tensor' ): return tf.is_symbolic_tensor(lowerCamelCase ) return type(lowerCamelCase ) == tf.Tensor def a_ ( lowerCamelCase ): return False if not is_tf_available() else _is_tf_symbolic_tensor(lowerCamelCase ) def a_ ( lowerCamelCase ): import jax.numpy as jnp # noqa: F811 return isinstance(lowerCamelCase , jnp.ndarray ) def a_ ( lowerCamelCase ): return False if not is_flax_available() else _is_jax(lowerCamelCase ) def a_ ( lowerCamelCase ): if isinstance(lowerCamelCase , (dict, UserDict) ): return {k: to_py_obj(lowerCamelCase ) for k, v in obj.items()} elif isinstance(lowerCamelCase , (list, tuple) ): return [to_py_obj(lowerCamelCase ) for o in obj] elif is_tf_tensor(lowerCamelCase ): return obj.numpy().tolist() elif is_torch_tensor(lowerCamelCase ): return obj.detach().cpu().tolist() elif is_jax_tensor(lowerCamelCase ): return np.asarray(lowerCamelCase ).tolist() elif isinstance(lowerCamelCase , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def a_ ( lowerCamelCase ): if isinstance(lowerCamelCase , (dict, UserDict) ): return {k: to_numpy(lowerCamelCase ) for k, v in obj.items()} elif isinstance(lowerCamelCase , (list, tuple) ): return np.array(lowerCamelCase ) elif is_tf_tensor(lowerCamelCase ): return obj.numpy() elif is_torch_tensor(lowerCamelCase ): return obj.detach().cpu().numpy() elif is_jax_tensor(lowerCamelCase ): return np.asarray(lowerCamelCase ) else: return obj class snake_case ( __UpperCAmelCase ): """simple docstring""" def __lowerCAmelCase ( self : List[Any] ): UpperCAmelCase__ = fields(self ) # Safety and consistency checks if not len(lowerCamelCase__ ): raise ValueError(f'''{self.__class__.__name__} has no fields.''' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.''' ) UpperCAmelCase__ = getattr(self ,class_fields[0].name ) UpperCAmelCase__ = all(getattr(self ,field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(lowerCamelCase__ ): if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): UpperCAmelCase__ = first_field.items() UpperCAmelCase__ = True else: try: UpperCAmelCase__ = iter(lowerCamelCase__ ) UpperCAmelCase__ = True except TypeError: UpperCAmelCase__ = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(lowerCamelCase__ ): if ( not isinstance(lowerCamelCase__ ,(list, tuple) ) or not len(lowerCamelCase__ ) == 2 or not isinstance(element[0] ,lowerCamelCase__ ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute UpperCAmelCase__ = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).''' ) break setattr(self ,element[0] ,element[1] ) if element[1] is not None: UpperCAmelCase__ = element[1] elif first_field is not None: UpperCAmelCase__ = first_field else: for field in class_fields: UpperCAmelCase__ = getattr(self ,field.name ) if v is not None: UpperCAmelCase__ = v def __delitem__( self : Union[str, Any] ,*lowerCamelCase__ : List[str] ,**lowerCamelCase__ : Dict ): raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.''' ) def __lowerCAmelCase ( self : Optional[int] ,*lowerCamelCase__ : List[str] ,**lowerCamelCase__ : str ): raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.''' ) def __lowerCAmelCase ( self : str ,*lowerCamelCase__ : Any ,**lowerCamelCase__ : Union[str, Any] ): raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.''' ) def __lowerCAmelCase ( self : str ,*lowerCamelCase__ : Optional[Any] ,**lowerCamelCase__ : List[Any] ): raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.''' ) def __getitem__( self : List[str] ,lowerCamelCase__ : List[Any] ): if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): UpperCAmelCase__ = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : Optional[int] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[int] ): if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(lowerCamelCase__ ,lowerCamelCase__ ) super().__setattr__(lowerCamelCase__ ,lowerCamelCase__ ) def __setitem__( self : Optional[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Dict ): # Will raise a KeyException if needed super().__setitem__(lowerCamelCase__ ,lowerCamelCase__ ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(lowerCamelCase__ ,lowerCamelCase__ ) def __lowerCAmelCase ( self : Optional[int] ): return tuple(self[k] for k in self.keys() ) class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): """simple docstring""" @classmethod def __lowerCAmelCase ( cls : List[str] ,lowerCamelCase__ : List[Any] ): raise ValueError( f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}''' ) class snake_case ( __UpperCAmelCase ): """simple docstring""" snake_case__ = "longest" snake_case__ = "max_length" snake_case__ = "do_not_pad" class snake_case ( __UpperCAmelCase ): """simple docstring""" snake_case__ = "pt" snake_case__ = "tf" snake_case__ = "np" snake_case__ = "jax" class snake_case : """simple docstring""" def __init__( self : Tuple ,lowerCamelCase__ : List[ContextManager] ): UpperCAmelCase__ = context_managers UpperCAmelCase__ = ExitStack() def __enter__( self : Union[str, Any] ): for context_manager in self.context_managers: self.stack.enter_context(lowerCamelCase__ ) def __exit__( self : Union[str, Any] ,*lowerCamelCase__ : Optional[Any] ,**lowerCamelCase__ : Dict ): self.stack.__exit__(*lowerCamelCase__ ,**lowerCamelCase__ ) def a_ ( lowerCamelCase ): UpperCAmelCase__ = infer_framework(lowerCamelCase ) if framework == "tf": UpperCAmelCase__ = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": UpperCAmelCase__ = inspect.signature(model_class.forward ) # PyTorch models else: UpperCAmelCase__ = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def a_ ( lowerCamelCase ): UpperCAmelCase__ = model_class.__name__ UpperCAmelCase__ = infer_framework(lowerCamelCase ) if framework == "tf": UpperCAmelCase__ = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": UpperCAmelCase__ = inspect.signature(model_class.forward ) # PyTorch models else: UpperCAmelCase__ = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def a_ ( lowerCamelCase , lowerCamelCase = "" , lowerCamelCase = "." ): def _flatten_dict(lowerCamelCase , lowerCamelCase="" , lowerCamelCase="." ): for k, v in d.items(): UpperCAmelCase__ = str(lowerCamelCase ) + delimiter + str(lowerCamelCase ) if parent_key else k if v and isinstance(lowerCamelCase , lowerCamelCase ): yield from flatten_dict(lowerCamelCase , lowerCamelCase , delimiter=lowerCamelCase ).items() else: yield key, v return dict(_flatten_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) ) @contextmanager def a_ ( lowerCamelCase , lowerCamelCase = False ): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def a_ ( lowerCamelCase , lowerCamelCase=None ): if is_numpy_array(lowerCamelCase ): return np.transpose(lowerCamelCase , axes=lowerCamelCase ) elif is_torch_tensor(lowerCamelCase ): return array.T if axes is None else array.permute(*lowerCamelCase ) elif is_tf_tensor(lowerCamelCase ): import tensorflow as tf return tf.transpose(lowerCamelCase , perm=lowerCamelCase ) elif is_jax_tensor(lowerCamelCase ): return jnp.transpose(lowerCamelCase , axes=lowerCamelCase ) else: raise ValueError(f'''Type not supported for transpose: {type(lowerCamelCase )}.''' ) def a_ ( lowerCamelCase , lowerCamelCase ): if is_numpy_array(lowerCamelCase ): return np.reshape(lowerCamelCase , lowerCamelCase ) elif is_torch_tensor(lowerCamelCase ): return array.reshape(*lowerCamelCase ) elif is_tf_tensor(lowerCamelCase ): import tensorflow as tf return tf.reshape(lowerCamelCase , lowerCamelCase ) elif is_jax_tensor(lowerCamelCase ): return jnp.reshape(lowerCamelCase , lowerCamelCase ) else: raise ValueError(f'''Type not supported for reshape: {type(lowerCamelCase )}.''' ) def a_ ( lowerCamelCase , lowerCamelCase=None ): if is_numpy_array(lowerCamelCase ): return np.squeeze(lowerCamelCase , axis=lowerCamelCase ) elif is_torch_tensor(lowerCamelCase ): return array.squeeze() if axis is None else array.squeeze(dim=lowerCamelCase ) elif is_tf_tensor(lowerCamelCase ): import tensorflow as tf return tf.squeeze(lowerCamelCase , axis=lowerCamelCase ) elif is_jax_tensor(lowerCamelCase ): return jnp.squeeze(lowerCamelCase , axis=lowerCamelCase ) else: raise ValueError(f'''Type not supported for squeeze: {type(lowerCamelCase )}.''' ) def a_ ( lowerCamelCase , lowerCamelCase ): if is_numpy_array(lowerCamelCase ): return np.expand_dims(lowerCamelCase , lowerCamelCase ) elif is_torch_tensor(lowerCamelCase ): return array.unsqueeze(dim=lowerCamelCase ) elif is_tf_tensor(lowerCamelCase ): import tensorflow as tf return tf.expand_dims(lowerCamelCase , axis=lowerCamelCase ) elif is_jax_tensor(lowerCamelCase ): return jnp.expand_dims(lowerCamelCase , axis=lowerCamelCase ) else: raise ValueError(f'''Type not supported for expand_dims: {type(lowerCamelCase )}.''' ) def a_ ( lowerCamelCase ): if is_numpy_array(lowerCamelCase ): return np.size(lowerCamelCase ) elif is_torch_tensor(lowerCamelCase ): return array.numel() elif is_tf_tensor(lowerCamelCase ): import tensorflow as tf return tf.size(lowerCamelCase ) elif is_jax_tensor(lowerCamelCase ): return array.size else: raise ValueError(f'''Type not supported for expand_dims: {type(lowerCamelCase )}.''' ) def a_ ( lowerCamelCase , lowerCamelCase ): for key, value in auto_map.items(): if isinstance(lowerCamelCase , (tuple, list) ): UpperCAmelCase__ = [f'''{repo_id}--{v}''' if (v is not None and '--' not in v) else v for v in value] elif value is not None and "--" not in value: UpperCAmelCase__ = f'''{repo_id}--{value}''' return auto_map def a_ ( lowerCamelCase ): for base_class in inspect.getmro(lowerCamelCase ): UpperCAmelCase__ = base_class.__module__ UpperCAmelCase__ = base_class.__name__ if module.startswith('tensorflow' ) or module.startswith('keras' ) or name == "TFPreTrainedModel": return "tf" elif module.startswith('torch' ) or name == "PreTrainedModel": return "pt" elif module.startswith('flax' ) or module.startswith('jax' ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f'''Could not infer framework from class {model_class}.''' )
98
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 35 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : Optional[Any] = x_den * y_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : Optional[int] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : List[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Any = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Optional[int] = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 __a : int = x_num * y_num __a : Optional[Any] = x_den * y_num + x_num * y_den __a : Tuple = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : List[Any] = x_num * x_num * y_num * y_num __a : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : Optional[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
27
0
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 lowercase : List[str] = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right lowercase : Any = 2_5_0_0_0_4 lowercase : Optional[int] = 2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class A__ ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : Dict = MBartaaTokenizer __A : Any = MBartaaTokenizerFast __A : Any = True __A : Tuple = True def __lowercase ( self) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing a__ : str = MBartaaTokenizer(lowercase , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=lowercase) tokenizer.save_pretrained(self.tmpdirname) def __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : Dict = '<s>' a__ : Union[str, Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase) , lowercase) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase) , lowercase) def __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : Tuple = 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(lowercase) , 1054) def __lowercase ( self) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1054) def __lowercase ( self) -> str: '''simple docstring''' a__ : Any = MBartaaTokenizer(lowercase , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=lowercase) a__ : Dict = tokenizer.tokenize('This is a test') self.assertListEqual(lowercase , ['▁This', '▁is', '▁a', '▁t', 'est']) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) a__ : List[Any] = tokenizer.tokenize('I was born in 92000, and this is falsé.') self.assertListEqual( lowercase , [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', 'é', '.'] , ) a__ : Optional[Any] = tokenizer.convert_tokens_to_ids(lowercase) self.assertListEqual( lowercase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) a__ : Optional[Any] = tokenizer.convert_ids_to_tokens(lowercase) self.assertListEqual( lowercase , [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 __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : List[str] = {'input_ids': [[25_0004, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [25_0004, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 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], [25_0004, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 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=lowercase , model_name='facebook/mbart-large-50' , revision='d3913889c59cd5c9e456b269c376325eabad57e2' , ) def __lowercase ( self) -> Any: '''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 a__ : Dict = (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})'): a__ : Tuple = self.rust_tokenizer_class.from_pretrained(lowercase , **lowercase) a__ : List[str] = self.tokenizer_class.from_pretrained(lowercase , **lowercase) a__ : int = tempfile.mkdtemp() a__ : Dict = tokenizer_r.save_pretrained(lowercase) a__ : Union[str, Any] = tokenizer_p.save_pretrained(lowercase) # 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)) a__ : Any = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f) self.assertSequenceEqual(lowercase , lowercase) # Checks everything loads correctly in the same way a__ : Any = tokenizer_r.from_pretrained(lowercase) a__ : Any = tokenizer_p.from_pretrained(lowercase) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase , lowercase)) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowercase) # Save tokenizer rust, legacy_format=True a__ : Any = tempfile.mkdtemp() a__ : str = tokenizer_r.save_pretrained(lowercase , legacy_format=lowercase) a__ : Dict = tokenizer_p.save_pretrained(lowercase) # Checks it save with the same files self.assertSequenceEqual(lowercase , lowercase) # Checks everything loads correctly in the same way a__ : Union[str, Any] = tokenizer_r.from_pretrained(lowercase) a__ : Optional[Any] = tokenizer_p.from_pretrained(lowercase) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase , lowercase)) shutil.rmtree(lowercase) # Save tokenizer rust, legacy_format=False a__ : Any = tempfile.mkdtemp() a__ : Optional[int] = tokenizer_r.save_pretrained(lowercase , legacy_format=lowercase) a__ : str = tokenizer_p.save_pretrained(lowercase) # 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 a__ : List[str] = tokenizer_r.from_pretrained(lowercase) a__ : Dict = tokenizer_p.from_pretrained(lowercase) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase , lowercase)) shutil.rmtree(lowercase) @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase ): """simple docstring""" __A : str = '''facebook/mbart-large-50-one-to-many-mmt''' __A : Union[str, Any] = [ ''' 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.''', ] __A : Dict = [ '''Ş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.''', ] __A : List[Any] = [EN_CODE, 8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2] @classmethod def __lowercase ( cls) -> Any: '''simple docstring''' a__ : MBartaaTokenizer = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO') a__ : Dict = 1 return cls def __lowercase ( self) -> List[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 25_0001) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 25_0004) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 25_0020) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'] , 25_0038) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Optional[Any] = self.tokenizer.batch_encode_plus(self.src_text).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowercase) def __lowercase ( self) -> Dict: '''simple docstring''' self.assertIn(lowercase , self.tokenizer.all_special_ids) a__ : Any = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] a__ : Any = self.tokenizer.decode(lowercase , skip_special_tokens=lowercase) a__ : List[str] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowercase) self.assertEqual(lowercase , lowercase) self.assertNotIn(self.tokenizer.eos_token , lowercase) def __lowercase ( self) -> int: '''simple docstring''' a__ : Tuple = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , lowercase) a__ : str = 10 a__ : Optional[Any] = self.tokenizer(lowercase , max_length=lowercase , truncation=lowercase).input_ids[0] self.assertEqual(ids[0] , lowercase) self.assertEqual(ids[-1] , 2) self.assertEqual(len(lowercase) , lowercase) def __lowercase ( self) -> List[Any]: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR']) , [25_0053, 25_0001]) def __lowercase ( self) -> Dict: '''simple docstring''' a__ : List[Any] = tempfile.mkdtemp() a__ : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowercase) a__ : Optional[int] = MBartaaTokenizer.from_pretrained(lowercase) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowercase) @require_torch def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Union[str, Any] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowercase , return_tensors='pt') a__ : 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 __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : List[Any] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowercase , truncation=lowercase , max_length=len(self.expected_src_tokens) , return_tensors='pt' , ) a__ : Optional[int] = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id) self.assertIsInstance(lowercase , lowercase) self.assertEqual((2, 14) , batch.input_ids.shape) self.assertEqual((2, 14) , batch.attention_mask.shape) a__ : Union[str, Any] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowercase) 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 __lowercase ( self) -> str: '''simple docstring''' a__ : Any = self.tokenizer(self.src_text , padding=lowercase , truncation=lowercase , max_length=3 , return_tensors='pt') a__ : int = self.tokenizer( text_target=self.tgt_text , padding=lowercase , truncation=lowercase , max_length=10 , return_tensors='pt') a__ : Optional[int] = targets['input_ids'] a__ : Optional[Any] = shift_tokens_right(lowercase , self.tokenizer.pad_token_id) self.assertEqual(batch.input_ids.shape[1] , 3) self.assertEqual(batch.decoder_input_ids.shape[1] , 10) @require_torch def __lowercase ( self) -> int: '''simple docstring''' a__ : Tuple = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR') self.assertEqual( nested_simplify(lowercase) , { # en_XX, A, test, EOS 'input_ids': [[25_0004, 62, 3034, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 25_0001, } , )
99
'''simple docstring''' import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): @property def __UpperCAmelCase ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ort.SessionOptions() __a : Dict = False return options def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) __a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default __a : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__a , feature_extractor=__a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__a ) __a : Tuple = 'A red cat sitting on a park bench' __a : int = np.random.RandomState(0 ) __a : Tuple = pipe( prompt=__a , image=__a , mask_image=__a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=__a , output_type='np' , ) __a : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
27
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { "microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json", # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" __lowercase : Tuple = '''biogpt''' def __init__( self , lowerCAmelCase__=4_2_3_8_4 , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=2_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=4_0_9_6 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , **lowerCAmelCase__ , ): __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = scale_embedding __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = layerdrop __SCREAMING_SNAKE_CASE = activation_dropout super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__)
100
'''simple docstring''' import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowercase : Dict = 16 __lowercase : List[Any] = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return int(x / 2**20 ) class __UpperCamelCase : def __enter__( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero __a : Optional[int] = torch.cuda.memory_allocated() return self def __exit__( self , *__a ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() __a : Dict = torch.cuda.memory_allocated() __a : List[Any] = torch.cuda.max_memory_allocated() __a : Tuple = bamb(self.end - self.begin ) __a : Tuple = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def lowerCamelCase (_SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : int = 16 , _SCREAMING_SNAKE_CASE : str = "bert-base-cased" , _SCREAMING_SNAKE_CASE : int = 320 , _SCREAMING_SNAKE_CASE : int = 160 , ): __a : int = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : List[Any] = load_dataset( 'glue' , 'mrpc' , split={'train': F"""train[:{n_train}]""", 'validation': F"""validation[:{n_val}]"""} ) def tokenize_function(_SCREAMING_SNAKE_CASE : Tuple ): # max_length=None => use the model max length (it's actually the default) __a : Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a : List[str] = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=_SCREAMING_SNAKE_CASE ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : Tuple = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. __a : int = DataLoader( tokenized_datasets['train'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) __a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): # Initialize accelerator __a : str = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : Dict = config['lr'] __a : str = int(config['num_epochs'] ) __a : Optional[int] = int(config['seed'] ) __a : Any = int(config['batch_size'] ) __a : List[str] = args.model_name_or_path set_seed(_SCREAMING_SNAKE_CASE ) __a , __a : int = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : Optional[int] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE ) # Instantiate optimizer __a : Optional[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a : Optional[Any] = optimizer_cls(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) if accelerator.state.deepspeed_plugin is not None: __a : int = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: __a : Union[str, Any] = 1 __a : Tuple = (len(_SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a : str = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=0 , num_training_steps=_SCREAMING_SNAKE_CASE , ) else: __a : List[Any] = DummyScheduler(_SCREAMING_SNAKE_CASE , total_num_steps=_SCREAMING_SNAKE_CASE , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a : Optional[Any] = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # We need to keep track of how many total steps we have iterated over __a : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly __a : Dict = 0 # Now we train the model __a : str = {} for epoch in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): __a : List[Any] = model(**_SCREAMING_SNAKE_CASE ) __a : str = outputs.loss __a : str = loss / gradient_accumulation_steps accelerator.backward(_SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin ) ) ) accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used ) ) accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked ) ) accelerator.print( 'Total Peak Memory consumed during the train (max): {}'.format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) __a : List[Any] = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'peak_memory_utilization.json' ) , 'w' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (): __a : int = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=_SCREAMING_SNAKE_CASE , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_SCREAMING_SNAKE_CASE , ) parser.add_argument( '--output_dir' , type=_SCREAMING_SNAKE_CASE , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--peak_memory_upper_bound' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.' , ) parser.add_argument( '--n_train' , type=_SCREAMING_SNAKE_CASE , default=320 , help='Number of training examples to use.' , ) parser.add_argument( '--n_val' , type=_SCREAMING_SNAKE_CASE , default=160 , help='Number of validation examples to use.' , ) parser.add_argument( '--num_epochs' , type=_SCREAMING_SNAKE_CASE , default=1 , help='Number of train epochs.' , ) __a : List[str] = parser.parse_args() __a : List[Any] = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
27
0