code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""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 __magic_name__ = logging.get_logger(__name__) __magic_name__ = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" a_ : str ="mobilenet_v1" def __init__( self : Optional[int] , _snake_case : List[Any]=3 , _snake_case : Optional[Any]=224 , _snake_case : Optional[int]=1.0 , _snake_case : List[str]=8 , _snake_case : str="relu6" , _snake_case : List[Any]=True , _snake_case : str=0.999 , _snake_case : Union[str, Any]=0.02 , _snake_case : str=0.001 , **_snake_case : Union[str, Any] , ) -> int: '''simple docstring''' super().__init__(**lowerCamelCase__ ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) a__ = num_channels a__ = image_size a__ = depth_multiplier a__ = min_depth a__ = hidden_act a__ = tf_padding a__ = classifier_dropout_prob a__ = initializer_range a__ = layer_norm_eps class SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" a_ : Dict =version.parse("1.11" ) @property def _lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def _lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' 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 : List[Any] ) -> Optional[Any]: '''simple docstring''' return 1E-4
232
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE_:List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_:List[Any] = { """google/bit-50""": """https://huggingface.co/google/bit-50/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __lowerCamelCase : Optional[Any] = "bit" __lowerCamelCase : Union[str, Any] = ["preactivation", "bottleneck"] __lowerCamelCase : Union[str, Any] = ["SAME", "VALID"] def __init__( self, lowerCamelCase__=3, lowerCamelCase__=64, lowerCamelCase__=[256, 512, 1024, 2048], lowerCamelCase__=[3, 4, 6, 3], lowerCamelCase__="preactivation", lowerCamelCase__="relu", lowerCamelCase__=None, lowerCamelCase__=32, lowerCamelCase__=0.0, lowerCamelCase__=False, lowerCamelCase__=32, lowerCamelCase__=1, lowerCamelCase__=None, lowerCamelCase__=None, **lowerCamelCase__, ): super().__init__(**lowerCamelCase__ ) if layer_type not in self.layer_types: raise ValueError(f'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) if global_padding is not None: if global_padding.upper() in self.supported_padding: A : List[Any] = global_padding.upper() else: raise ValueError(f'''Padding strategy {global_padding} not supported''' ) A : Dict = num_channels A : List[Any] = embedding_size A : Optional[Any] = hidden_sizes A : str = depths A : str = layer_type A : Union[str, Any] = hidden_act A : Any = global_padding A : Optional[int] = num_groups A : Dict = drop_path_rate A : List[Any] = embedding_dynamic_padding A : List[Any] = output_stride A : Union[str, Any] = width_factor A : Dict = ["""stem"""] + [f'''stage{idx}''' for idx in range(1, len(lowerCamelCase__ ) + 1 )] A , A : Any = get_aligned_output_features_output_indices( out_features=lowerCamelCase__, out_indices=lowerCamelCase__, stage_names=self.stage_names )
662
0
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ : str = { """deepmind/language-perceiver""": """https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json""", # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase = "perceiver" def __init__( self : Optional[Any] , __lowerCamelCase : int=256 , __lowerCamelCase : List[str]=1_280 , __lowerCamelCase : int=768 , __lowerCamelCase : str=1 , __lowerCamelCase : Any=26 , __lowerCamelCase : Dict=8 , __lowerCamelCase : Any=8 , __lowerCamelCase : str=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]="kv" , __lowerCamelCase : Dict=1 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : Any=0.1 , __lowerCamelCase : int=0.02 , __lowerCamelCase : Union[str, Any]=1E-1_2 , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[Any]=262 , __lowerCamelCase : Optional[Any]=2_048 , __lowerCamelCase : List[str]=56 , __lowerCamelCase : Optional[int]=[368, 496] , __lowerCamelCase : int=16 , __lowerCamelCase : Optional[Any]=1_920 , __lowerCamelCase : Union[str, Any]=16 , __lowerCamelCase : Any=[1, 16, 224, 224] , **__lowerCamelCase : List[str] , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**lowerCamelCase__ ) __lowercase = num_latents __lowercase = d_latents __lowercase = d_model __lowercase = num_blocks __lowercase = num_self_attends_per_block __lowercase = num_self_attention_heads __lowercase = num_cross_attention_heads __lowercase = qk_channels __lowercase = v_channels __lowercase = cross_attention_shape_for_attention __lowercase = self_attention_widening_factor __lowercase = cross_attention_widening_factor __lowercase = hidden_act __lowercase = attention_probs_dropout_prob __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = use_query_residual # masked language modeling attributes __lowercase = vocab_size __lowercase = max_position_embeddings # image classification attributes __lowercase = image_size # flow attributes __lowercase = train_size # multimodal autoencoding attributes __lowercase = num_frames __lowercase = audio_samples_per_frame __lowercase = samples_per_patch __lowercase = output_shape class snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @property def UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if self.task == "multiple-choice": __lowercase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __lowercase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ('inputs', dynamic_axis), ('attention_mask', dynamic_axis), ] ) @property def UpperCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' return 1E-4 def UpperCAmelCase ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : Optional[int] = -1 , __lowerCamelCase : Any = -1 , __lowerCamelCase : Dict = -1 , __lowerCamelCase : List[Any] = False , __lowerCamelCase : Dict = None , __lowerCamelCase : List[str] = 3 , __lowerCamelCase : Union[str, Any] = 40 , __lowerCamelCase : Optional[int] = 40 , ) -> Optional[Any]: '''simple docstring''' if isinstance(lowerCamelCase__ , lowerCamelCase__ ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __lowercase = compute_effective_axis_dimension( lowerCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __lowercase = preprocessor.num_special_tokens_to_add(lowerCamelCase__ ) __lowercase = compute_effective_axis_dimension( lowerCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCamelCase__ ) # Generate dummy inputs according to compute batch and sequence __lowercase = [""" """.join(['a'] ) * seq_length] * batch_size __lowercase = dict(preprocessor(lowerCamelCase__ , return_tensors=lowerCamelCase__ ) ) __lowercase = inputs.pop('input_ids' ) return inputs elif isinstance(lowerCamelCase__ , lowerCamelCase__ ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __lowercase = compute_effective_axis_dimension(lowerCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch ) __lowercase = self._generate_dummy_images(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowercase = dict(preprocessor(images=lowerCamelCase__ , return_tensors=lowerCamelCase__ ) ) __lowercase = inputs.pop('pixel_values' ) return inputs else: raise ValueError( 'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
375
import unittest from transformers import BertGenerationConfig, 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, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self, lowerCamelCase__, lowerCamelCase__=13, lowerCamelCase__=7, lowerCamelCase__=True, lowerCamelCase__=True, lowerCamelCase__=99, lowerCamelCase__=32, lowerCamelCase__=5, lowerCamelCase__=4, lowerCamelCase__=37, lowerCamelCase__="gelu", lowerCamelCase__=0.1, lowerCamelCase__=0.1, lowerCamelCase__=50, lowerCamelCase__=0.02, lowerCamelCase__=True, lowerCamelCase__=None, ): A : List[str] = parent A : List[str] = batch_size A : Optional[int] = seq_length A : Optional[int] = is_training A : Tuple = use_input_mask A : Optional[Any] = vocab_size A : str = hidden_size A : Any = num_hidden_layers A : List[Any] = num_attention_heads A : Optional[int] = intermediate_size A : int = hidden_act A : Dict = hidden_dropout_prob A : Optional[Any] = attention_probs_dropout_prob A : List[Any] = max_position_embeddings A : int = initializer_range A : Tuple = use_labels A : List[str] = scope def _lowerCAmelCase ( self ): A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) A : int = None if self.use_input_mask: A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A : Tuple = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) A : List[Any] = self.get_config() return config, input_ids, input_mask, token_labels def _lowerCAmelCase ( self ): return BertGenerationConfig( 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, is_decoder=lowerCamelCase__, initializer_range=self.initializer_range, ) def _lowerCAmelCase ( self ): ( ( A ) , ( A ) , ( A ) , ( A ) , ) : List[Any] = self.prepare_config_and_inputs() A : Any = True A : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__, ): A : str = BertGenerationEncoder(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() A : Optional[int] = model(lowerCamelCase__, attention_mask=lowerCamelCase__ ) A : List[str] = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__, ): A : List[str] = True A : Union[str, Any] = BertGenerationEncoder(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() A : Any = model( lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, ) A : Optional[Any] = model( lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__, ): A : Union[str, Any] = True A : Optional[int] = True A : Optional[int] = BertGenerationDecoder(config=lowerCamelCase__ ).to(lowerCamelCase__ ).eval() # first forward pass A : int = model( lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, use_cache=lowerCamelCase__, ) A : List[str] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : Optional[Any] = ids_tensor((self.batch_size, 3), config.vocab_size ) A : int = ids_tensor((self.batch_size, 3), vocab_size=2 ) # append to next input_ids and A : List[str] = torch.cat([input_ids, next_tokens], dim=-1 ) A : Union[str, Any] = torch.cat([input_mask, next_mask], dim=-1 ) A : List[str] = model( lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, output_hidden_states=lowerCamelCase__, )["""hidden_states"""][0] A : Any = model( lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, past_key_values=lowerCamelCase__, output_hidden_states=lowerCamelCase__, )["""hidden_states"""][0] # select random slice A : Any = ids_tensor((1,), output_from_past.shape[-1] ).item() A : Tuple = output_from_no_past[:, -3:, random_slice_idx].detach() A : Dict = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase__, lowerCamelCase__, atol=1e-3 ) ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, *lowerCamelCase__, ): A : Optional[int] = BertGenerationDecoder(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() A : List[str] = model(lowerCamelCase__, attention_mask=lowerCamelCase__, labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self ): A , A , A , A : str = self.prepare_config_and_inputs() A : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Any = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __lowerCamelCase : int = (BertGenerationDecoder,) if is_torch_available() else () __lowerCamelCase : List[Any] = ( {"feature-extraction": BertGenerationEncoder, "text-generation": BertGenerationDecoder} if is_torch_available() else {} ) def _lowerCAmelCase ( self ): A : Any = BertGenerationEncoderTester(self ) A : Optional[int] = ConfigTester(self, config_class=lowerCamelCase__, hidden_size=37 ) def _lowerCAmelCase ( self ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self ): A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def _lowerCAmelCase ( self ): A , A , A , A : Optional[Any] = self.model_tester.prepare_config_and_inputs() A : Any = """bert""" self.model_tester.create_and_check_model(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCamelCase__ ) def _lowerCAmelCase ( self ): # This regression test was failing with PyTorch < 1.3 ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() A : int = None self.model_tester.create_and_check_model_as_decoder( lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, ) def _lowerCAmelCase ( self ): A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*lowerCamelCase__ ) @slow def _lowerCAmelCase ( self ): A : Tuple = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) self.assertIsNotNone(lowerCamelCase__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' @slow def _lowerCAmelCase ( self ): A : Optional[int] = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) A : Optional[int] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): A : Union[str, Any] = model(lowerCamelCase__ )[0] A : List[Any] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape, lowerCamelCase__ ) A : Tuple = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3], lowerCamelCase__, atol=1e-4 ) ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' @slow def _lowerCAmelCase ( self ): A : Optional[Any] = BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) A : List[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): A : Dict = model(lowerCamelCase__ )[0] A : List[str] = torch.Size([1, 8, 5_0358] ) self.assertEqual(output.shape, lowerCamelCase__ ) A : Optional[Any] = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3], lowerCamelCase__, atol=1e-4 ) )
662
0
from __future__ import annotations import typing from collections.abc import Iterable import numpy as np lowerCAmelCase : List[Any] = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 lowerCAmelCase : int = typing.Union[np.floataa, int, float] # noqa: UP007 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return np.sqrt(np.sum((np.asarray(_lowerCAmelCase ) - np.asarray(_lowerCAmelCase )) ** 2 ) ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return sum((va - va) ** 2 for va, va in zip(_lowerCAmelCase , _lowerCAmelCase ) ) ** (1 / 2) if __name__ == "__main__": def A_ ( ): from timeit import timeit print("Without Numpy" ) print( timeit( "euclidean_distance_no_np([1, 2, 3], [4, 5, 6])" , number=1_00_00 , globals=globals() , ) ) print("With Numpy" ) print( timeit( "euclidean_distance([1, 2, 3], [4, 5, 6])" , number=1_00_00 , globals=globals() , ) ) benchmark()
671
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_:Union[str, Any] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __lowerCamelCase : str = ["pixel_values"] def __init__( self, lowerCamelCase__ = True, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = PILImageResampling.BILINEAR, lowerCamelCase__ = True, lowerCamelCase__ = 1 / 255, lowerCamelCase__ = True, lowerCamelCase__ = None, lowerCamelCase__ = None, **lowerCamelCase__, ): super().__init__(**lowerCamelCase__ ) A : Union[str, Any] = size if size is not None else {"""shortest_edge""": 384} A : Optional[Any] = get_size_dict(lowerCamelCase__, default_to_square=lowerCamelCase__ ) A : Optional[Any] = do_resize A : Dict = size # Default value set here for backwards compatibility where the value in config is None A : Dict = crop_pct if crop_pct is not None else 224 / 256 A : Optional[int] = resample A : List[str] = do_rescale A : Tuple = rescale_factor A : Optional[int] = do_normalize A : Optional[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A : Any = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ = PILImageResampling.BICUBIC, lowerCamelCase__ = None, **lowerCamelCase__, ): A : Tuple = get_size_dict(lowerCamelCase__, default_to_square=lowerCamelCase__ ) if "shortest_edge" not in size: raise ValueError(f'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}''' ) A : List[str] = size["""shortest_edge"""] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct A : int = int(shortest_edge / crop_pct ) A : List[Any] = get_resize_output_image_size(lowerCamelCase__, size=lowerCamelCase__, default_to_square=lowerCamelCase__ ) A : Any = resize(image=lowerCamelCase__, size=lowerCamelCase__, resample=lowerCamelCase__, data_format=lowerCamelCase__, **lowerCamelCase__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=lowerCamelCase__, size=(shortest_edge, shortest_edge), data_format=lowerCamelCase__, **lowerCamelCase__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( lowerCamelCase__, size=(shortest_edge, shortest_edge), resample=lowerCamelCase__, data_format=lowerCamelCase__, **lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ = None, **lowerCamelCase__, ): return rescale(lowerCamelCase__, scale=lowerCamelCase__, data_format=lowerCamelCase__, **lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ = None, **lowerCamelCase__, ): return normalize(lowerCamelCase__, mean=lowerCamelCase__, std=lowerCamelCase__, data_format=lowerCamelCase__, **lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = ChannelDimension.FIRST, **lowerCamelCase__, ): A : Dict = do_resize if do_resize is not None else self.do_resize A : Optional[int] = crop_pct if crop_pct is not None else self.crop_pct A : str = resample if resample is not None else self.resample A : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale A : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor A : Dict = do_normalize if do_normalize is not None else self.do_normalize A : List[str] = image_mean if image_mean is not None else self.image_mean A : Optional[Any] = image_std if image_std is not None else self.image_std A : Optional[Any] = size if size is not None else self.size A : str = get_size_dict(lowerCamelCase__, default_to_square=lowerCamelCase__ ) A : Any = make_list_of_images(lowerCamelCase__ ) if not valid_images(lowerCamelCase__ ): 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. A : List[Any] = [to_numpy_array(lowerCamelCase__ ) for image in images] if do_resize: A : Any = [self.resize(image=lowerCamelCase__, size=lowerCamelCase__, crop_pct=lowerCamelCase__, resample=lowerCamelCase__ ) for image in images] if do_rescale: A : str = [self.rescale(image=lowerCamelCase__, scale=lowerCamelCase__ ) for image in images] if do_normalize: A : Union[str, Any] = [self.normalize(image=lowerCamelCase__, mean=lowerCamelCase__, std=lowerCamelCase__ ) for image in images] A : Tuple = [to_channel_dimension_format(lowerCamelCase__, lowerCamelCase__ ) for image in images] A : Dict = {"""pixel_values""": images} return BatchFeature(data=lowerCamelCase__, tensor_type=lowerCamelCase__ )
662
0
from ...processing_utils import ProcessorMixin class snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCAmelCase = "SpeechT5FeatureExtractor" __lowerCAmelCase = "SpeechT5Tokenizer" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ ): super().__init__(lowerCamelCase__ , lowerCamelCase__ ) def __call__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): __lowercase = kwargs.pop("audio" , lowerCamelCase__ ) __lowercase = kwargs.pop("text" , lowerCamelCase__ ) __lowercase = kwargs.pop("text_target" , lowerCamelCase__ ) __lowercase = kwargs.pop("audio_target" , lowerCamelCase__ ) __lowercase = kwargs.pop("sampling_rate" , lowerCamelCase__ ) if audio is not None and text is not None: raise ValueError( "Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" ) if audio_target is not None and text_target is not None: raise ValueError( "Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( "You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." ) if audio is not None: __lowercase = self.feature_extractor(lowerCamelCase__ , *lowerCamelCase__ , sampling_rate=lowerCamelCase__ , **lowerCamelCase__ ) elif text is not None: __lowercase = self.tokenizer(lowerCamelCase__ , **lowerCamelCase__ ) else: __lowercase = None if audio_target is not None: __lowercase = self.feature_extractor(audio_target=lowerCamelCase__ , *lowerCamelCase__ , sampling_rate=lowerCamelCase__ , **lowerCamelCase__ ) __lowercase = targets["""input_values"""] elif text_target is not None: __lowercase = self.tokenizer(lowerCamelCase__ , **lowerCamelCase__ ) __lowercase = targets["""input_ids"""] else: __lowercase = None if inputs is None: return targets if targets is not None: __lowercase = labels __lowercase = targets.get("attention_mask" ) if decoder_attention_mask is not None: __lowercase = decoder_attention_mask return inputs def snake_case__ ( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): __lowercase = kwargs.pop("input_values" , lowerCamelCase__ ) __lowercase = kwargs.pop("input_ids" , lowerCamelCase__ ) __lowercase = kwargs.pop("labels" , lowerCamelCase__ ) if input_values is not None and input_ids is not None: raise ValueError("Cannot process both `input_values` and `input_ids` inputs." ) if input_values is None and input_ids is None and labels is None: raise ValueError( "You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." ) if input_values is not None: __lowercase = self.feature_extractor.pad(lowerCamelCase__ , *lowerCamelCase__ , **lowerCamelCase__ ) elif input_ids is not None: __lowercase = self.tokenizer.pad(lowerCamelCase__ , **lowerCamelCase__ ) else: __lowercase = None if labels is not None: if "input_ids" in labels or (isinstance(lowerCamelCase__ , lowerCamelCase__ ) and "input_ids" in labels[0]): __lowercase = self.tokenizer.pad(lowerCamelCase__ , **lowerCamelCase__ ) __lowercase = targets["""input_ids"""] else: __lowercase = self.feature_extractor.feature_size __lowercase = self.feature_extractor.num_mel_bins __lowercase = self.feature_extractor.pad(lowerCamelCase__ , *lowerCamelCase__ , **lowerCamelCase__ ) __lowercase = feature_size_hack __lowercase = targets["""input_values"""] else: __lowercase = None if inputs is None: return targets if targets is not None: __lowercase = labels __lowercase = targets.get("attention_mask" ) if decoder_attention_mask is not None: __lowercase = decoder_attention_mask return inputs def snake_case__ ( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): return self.tokenizer.batch_decode(*lowerCamelCase__ , **lowerCamelCase__ ) def snake_case__ ( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): return self.tokenizer.decode(*lowerCamelCase__ , **lowerCamelCase__ )
321
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_:Tuple = logging.get_logger(__name__) def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase=False , _lowerCAmelCase=False ) -> Any: """simple docstring""" A : Dict = """backbone.""" if is_semantic else """""" A : Union[str, Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''{prefix}blocks.{i}.norm1.weight''', f'''beit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.norm1.bias''', f'''beit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''{prefix}blocks.{i}.attn.proj.weight''', f'''beit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''{prefix}blocks.{i}.attn.proj.bias''', f'''beit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''{prefix}blocks.{i}.norm2.weight''', f'''beit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.norm2.bias''', f'''beit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc1.weight''', f'''beit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc1.bias''', f'''beit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc2.weight''', f'''beit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc2.bias''', f'''beit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ (f'''{prefix}cls_token''', """beit.embeddings.cls_token"""), (f'''{prefix}patch_embed.proj.weight''', """beit.embeddings.patch_embeddings.projection.weight"""), (f'''{prefix}patch_embed.proj.bias''', """beit.embeddings.patch_embeddings.projection.bias"""), (f'''{prefix}pos_embed''', """beit.embeddings.position_embeddings"""), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ("""mask_token""", """beit.embeddings.mask_token"""), ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ] ) else: # layernorm + classification head rename_keys.extend( [ ("""fc_norm.weight""", """beit.pooler.layernorm.weight"""), ("""fc_norm.bias""", """beit.pooler.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False , _lowerCAmelCase=False ) -> Any: """simple docstring""" for i in range(config.num_hidden_layers ): A : Dict = """backbone.""" if is_semantic else """""" # queries, keys and values A : Union[str, Any] = state_dict.pop(f'''{prefix}blocks.{i}.attn.qkv.weight''' ) A : Tuple = state_dict.pop(f'''{prefix}blocks.{i}.attn.q_bias''' ) A : Optional[int] = state_dict.pop(f'''{prefix}blocks.{i}.attn.v_bias''' ) A : int = in_proj_weight[ : config.hidden_size, : ] A : Any = q_bias A : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A : Tuple = in_proj_weight[ -config.hidden_size :, : ] A : Union[str, Any] = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained A : str = state_dict.pop(f'''{prefix}blocks.{i}.gamma_1''' ) A : List[Any] = state_dict.pop(f'''{prefix}blocks.{i}.gamma_2''' ) A : Dict = gamma_a A : Dict = gamma_a def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Dict: """simple docstring""" A : List[str] = dct.pop(_lowerCAmelCase ) A : Optional[Any] = val def __UpperCamelCase ( ) -> List[str]: """simple docstring""" A : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" A : Optional[Any] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ) return im @torch.no_grad() def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False ) -> str: """simple docstring""" A : Dict = False if """rvlcdip""" in checkpoint_url else True A : Union[str, Any] = BeitConfig(use_absolute_position_embeddings=_lowerCAmelCase , use_mask_token=_lowerCAmelCase ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: A : Dict = 1024 A : List[Any] = 4096 A : int = 24 A : int = 16 # labels if "rvlcdip" in checkpoint_url: A : List[Any] = 16 A : List[Any] = """huggingface/label-files""" A : int = """rvlcdip-id2label.json""" A : Dict = json.load(open(hf_hub_download(_lowerCAmelCase , _lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) A : List[str] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} A : int = idalabel A : Union[str, Any] = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys A : List[str] = torch.hub.load_state_dict_from_url(_lowerCAmelCase , map_location="""cpu""" )["""model"""] A : str = create_rename_keys(_lowerCAmelCase , has_lm_head=_lowerCAmelCase ) for src, dest in rename_keys: rename_key(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) read_in_q_k_v(_lowerCAmelCase , _lowerCAmelCase , has_lm_head=_lowerCAmelCase ) # load HuggingFace model A : Any = BeitForMaskedImageModeling(_lowerCAmelCase ) if has_lm_head else BeitForImageClassification(_lowerCAmelCase ) model.eval() model.load_state_dict(_lowerCAmelCase ) # Check outputs on an image A : Any = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=_lowerCAmelCase ) A : int = prepare_img() A : Tuple = image_processor(images=_lowerCAmelCase , return_tensors="""pt""" ) A : str = encoding["""pixel_values"""] A : Tuple = model(_lowerCAmelCase ) A : Optional[int] = outputs.logits # verify logits A : Tuple = [1, 16] if """rvlcdip""" in checkpoint_url else [1, 196, 8192] assert logits.shape == torch.Size(_lowerCAmelCase ), "Shape of logits not as expected" Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(_lowerCAmelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_lowerCAmelCase ) if push_to_hub: if has_lm_head: A : Any = """dit-base""" if """base""" in checkpoint_url else """dit-large""" else: A : List[Any] = """dit-base-finetuned-rvlcdip""" if """dit-b""" in checkpoint_url else """dit-large-finetuned-rvlcdip""" image_processor.push_to_hub( repo_path_or_name=Path(_lowerCAmelCase , _lowerCAmelCase ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=_lowerCAmelCase , ) model.push_to_hub( repo_path_or_name=Path(_lowerCAmelCase , _lowerCAmelCase ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=_lowerCAmelCase , ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_:Optional[int] = argparse.ArgumentParser() parser.add_argument( """--checkpoint_url""", default="""https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth""", type=str, help="""URL to the original PyTorch checkpoint (.pth file).""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", ) SCREAMING_SNAKE_CASE_:Optional[Any] = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
662
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a_ = logging.get_logger(__name__) a_ = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } a_ = { """vocab_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"""}, """merges_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"""}, """tokenizer_config_file""": { """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json""" }, } a_ = {"""facebook/blenderbot-3B""": 128} class __lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = ["input_ids", "attention_mask"] lowerCAmelCase__ = BlenderbotTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="replace" , __UpperCAmelCase="<s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="<s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="<mask>" , __UpperCAmelCase=False , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' super().__init__( lowerCamelCase__ , lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , errors=lowerCamelCase__ , bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , add_prefix_space=lowerCamelCase__ , trim_offsets=lowerCamelCase__ , **lowerCamelCase__ , ) __lowerCamelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , lowerCamelCase__ ) != add_prefix_space: __lowerCamelCase = getattr(lowerCamelCase__ , pre_tok_state.pop('''type''' ) ) __lowerCamelCase = add_prefix_space __lowerCamelCase = pre_tok_class(**lowerCamelCase__ ) __lowerCamelCase = add_prefix_space __lowerCamelCase = """post_processor""" __lowerCamelCase = getattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ ) if tokenizer_component_instance: __lowerCamelCase = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __lowerCamelCase = tuple(state['''sep'''] ) if "cls" in state: __lowerCamelCase = tuple(state['''cls'''] ) __lowerCamelCase = False if state.get('''add_prefix_space''' , lowerCamelCase__ ) != add_prefix_space: __lowerCamelCase = add_prefix_space __lowerCamelCase = True if state.get('''trim_offsets''' , lowerCamelCase__ ) != trim_offsets: __lowerCamelCase = trim_offsets __lowerCamelCase = True if changes_to_apply: __lowerCamelCase = getattr(lowerCamelCase__ , state.pop('''type''' ) ) __lowerCamelCase = component_class(**lowerCamelCase__ ) setattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def lowerCamelCase ( self ): '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else value __lowerCamelCase = value def lowerCamelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = kwargs.get('''is_split_into_words''' , lowerCamelCase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def lowerCamelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = kwargs.get('''is_split_into_words''' , lowerCamelCase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __lowerCamelCase = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ ) return tuple(lowerCamelCase__ ) def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(lowerCamelCase__ ) __lowerCamelCase = """ """.join(lowerCamelCase__ ) __lowerCamelCase = self.encode(lowerCamelCase__ ) if len(lowerCamelCase__ ) > self.model_max_length: __lowerCamelCase = input_ids[-self.model_max_length :] logger.warning(F"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens.""" ) return input_ids
175
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor SCREAMING_SNAKE_CASE_:Optional[int] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self, *lowerCamelCase__, **lowerCamelCase__ ): warnings.warn( """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use CLIPImageProcessor instead.""", lowerCamelCase__, ) super().__init__(*lowerCamelCase__, **lowerCamelCase__ )
662
0
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): _UpperCAmelCase : Union[str, Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _UpperCAmelCase : Optional[int] = 12_80_22 _UpperCAmelCase : List[str] = 12_80_28 @require_sentencepiece class lowerCAmelCase ( SCREAMING_SNAKE_CASE__, unittest.TestCase ): UpperCAmelCase__ = MaMaaaTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = True def A_ ( self : Union[str, Any] ) -> List[str]: super().setUp() lowerCamelCase__ : Optional[int] = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] lowerCamelCase__ : List[str] = dict(zip(lowerCamelCase__ , range(len(lowerCamelCase__ ) ) ) ) lowerCamelCase__ : int = Path(self.tmpdirname ) save_json(lowerCamelCase__ , save_dir / VOCAB_FILES_NAMES['vocab_file'] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(lowerCamelCase__ , save_dir / VOCAB_FILES_NAMES['spm_file'] ) lowerCamelCase__ : str = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def A_ ( self : List[Any] , **UpperCAmelCase : int ) -> Union[str, Any]: return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase__ ) def A_ ( self : Dict , UpperCAmelCase : Tuple ) -> Optional[int]: return ( "This is a test", "This is a test", ) def A_ ( self : List[str] ) -> Optional[int]: lowerCamelCase__ : Optional[Any] = """</s>""" lowerCamelCase__ : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase__ ) , lowerCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase__ ) , lowerCamelCase__ ) def A_ ( self : Any ) -> Optional[Any]: lowerCamelCase__ : Tuple = self.get_tokenizer() lowerCamelCase__ : List[Any] = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '</s>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '<s>' ) self.assertEqual(len(lowerCamelCase__ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('Skip this test while all models are still to be uploaded.' ) def A_ ( self : Dict ) -> Any: pass def A_ ( self : Any ) -> Tuple: lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : List[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(lowerCamelCase__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , [2, 3, 4, 5, 6] , ) lowerCamelCase__ : Optional[int] = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(lowerCamelCase__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) lowerCamelCase__ : Optional[int] = tokenizer.convert_tokens_to_string(lowerCamelCase__ ) self.assertEqual(lowerCamelCase__ , 'This is a test' ) @slow def A_ ( self : Optional[int] ) -> Optional[int]: # fmt: off lowerCamelCase__ : List[Any] = {"""input_ids""": [[128022, 110108, 397, 11, 38272, 2247, 124811, 285, 18105, 1586, 207, 7, 39534, 4428, 397, 1019, 18105, 1586, 207, 7, 41337, 16786, 241, 7, 20214, 17, 125690, 10398, 7, 44378, 58069, 68342, 7798, 7343, 11, 299, 33310, 4, 158, 37350, 94077, 4569, 299, 33310, 90, 4, 52840, 290, 4, 31270, 112, 299, 682, 4, 52840, 39953, 14079, 193, 52519, 90894, 17894, 120697, 11, 40445, 551, 17, 1019, 52519, 90894, 17756, 963, 11, 40445, 480, 17, 9792, 1120, 5173, 1393, 6240, 16786, 241, 120996, 28, 1245, 1393, 118240, 11123, 1019, 93612, 2691, 10618, 98058, 120409, 1928, 279, 4, 40683, 367, 178, 207, 1019, 103, 103121, 506, 65296, 5, 2], [128022, 21217, 367, 117, 125450, 128, 719, 7, 7308, 40, 93612, 12669, 1116, 16704, 71, 17785, 3699, 15592, 35, 144, 9584, 241, 11943, 713, 950, 799, 2247, 88427, 150, 149, 118813, 120706, 1019, 106906, 81518, 28, 1224, 22799, 397, 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], [128022, 1658, 123311, 5155, 5578, 4722, 279, 14947, 2366, 1120, 1197, 14, 1348, 9232, 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, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=lowerCamelCase__ , model_name='facebook/m2m100_418M' , revision='c168bae485c864188cf9aa0e4108b0b6934dc91e' , ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase ( unittest.TestCase ): UpperCAmelCase__ = "facebook/m2m100_418M" UpperCAmelCase__ = [ "In my opinion, there are two levels of response from the French government.", "NSA Affair Emphasizes Complete Lack of Debate on Intelligence", ] UpperCAmelCase__ = [ "Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.", "L'affaire NSA souligne l'absence totale de débat sur le renseignement", ] # fmt: off UpperCAmelCase__ = [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2] @classmethod def A_ ( cls : Dict ) -> Tuple: lowerCamelCase__ : MaMaaaTokenizer = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en' , tgt_lang='fr' ) lowerCamelCase__ : List[Any] = 1 return cls def A_ ( self : Optional[int] ) -> List[Any]: self.assertEqual(self.tokenizer.get_lang_id('ar' ) , 128006 ) self.assertEqual(self.tokenizer.get_lang_id('en' ) , 128022 ) self.assertEqual(self.tokenizer.get_lang_id('ro' ) , 128076 ) self.assertEqual(self.tokenizer.get_lang_id('mr' ) , 128063 ) def A_ ( self : str ) -> str: lowerCamelCase__ : int = self.tokenizer.get_vocab() self.assertEqual(len(lowerCamelCase__ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['<unk>'] , 3 ) self.assertIn(self.tokenizer.get_lang_token('en' ) , lowerCamelCase__ ) def A_ ( self : Optional[Any] ) -> str: lowerCamelCase__ : Any = """en""" lowerCamelCase__ : List[str] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCamelCase__ ) def A_ ( self : Any ) -> Union[str, Any]: self.assertIn(lowerCamelCase__ , self.tokenizer.all_special_ids ) # fmt: off lowerCamelCase__ : int = [FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 14028, 136, 3286, 9706, 6, 90797, 6, 144012, 162, 88128, 30061, 5, 2] # fmt: on lowerCamelCase__ : Dict = self.tokenizer.decode(lowerCamelCase__ , skip_special_tokens=lowerCamelCase__ ) lowerCamelCase__ : Any = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCamelCase__ ) self.assertEqual(lowerCamelCase__ , lowerCamelCase__ ) self.assertNotIn(self.tokenizer.eos_token , lowerCamelCase__ ) def A_ ( self : Any ) -> Union[str, Any]: lowerCamelCase__ : Dict = tempfile.mkdtemp() lowerCamelCase__ : Optional[int] = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(lowerCamelCase__ ) lowerCamelCase__ : str = MaMaaaTokenizer.from_pretrained(lowerCamelCase__ ) self.assertDictEqual(new_tok.lang_token_to_id , lowerCamelCase__ ) @require_torch def A_ ( self : Optional[Any] ) -> Optional[Any]: lowerCamelCase__ : List[Any] = """en""" lowerCamelCase__ : Optional[int] = """fr""" lowerCamelCase__ : Dict = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowerCamelCase__ , return_tensors='pt' ) lowerCamelCase__ : Any = shift_tokens_right( batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: lowerCamelCase__ : Tuple = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def A_ ( self : str ) -> Tuple: lowerCamelCase__ : str = """mr""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) lowerCamelCase__ : Dict = """zh""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def A_ ( self : str ) -> Any: lowerCamelCase__ : Optional[int] = """mr""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) lowerCamelCase__ : List[str] = """zh""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def A_ ( self : Any ) -> Tuple: lowerCamelCase__ : Dict = self.tokenizer._build_translation_inputs('A test' , return_tensors='pt' , src_lang='en' , tgt_lang='ar' ) self.assertEqual( nested_simplify(lowerCamelCase__ ) , { # en_XX, A, test, EOS 'input_ids': [[128022, 58, 4183, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 128006, } , )
295
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 SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self, lowerCamelCase__, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = False, lowerCamelCase__ = False, lowerCamelCase__ = None, **lowerCamelCase__, ): super().__init__( lowerCamelCase__, split=lowerCamelCase__, features=lowerCamelCase__, cache_dir=lowerCamelCase__, keep_in_memory=lowerCamelCase__, streaming=lowerCamelCase__, num_proc=lowerCamelCase__, **lowerCamelCase__, ) A : List[Any] = path_or_paths if isinstance(lowerCamelCase__, lowerCamelCase__ ) else {self.split: path_or_paths} A : str = Text( cache_dir=lowerCamelCase__, data_files=lowerCamelCase__, features=lowerCamelCase__, **lowerCamelCase__, ) def _lowerCAmelCase ( self ): # Build iterable dataset if self.streaming: A : int = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: A : List[str] = None A : Dict = None A : Tuple = None A : Tuple = None self.builder.download_and_prepare( download_config=lowerCamelCase__, download_mode=lowerCamelCase__, verification_mode=lowerCamelCase__, base_path=lowerCamelCase__, num_proc=self.num_proc, ) A : List[str] = self.builder.as_dataset( split=self.split, verification_mode=lowerCamelCase__, in_memory=self.keep_in_memory ) return dataset
662
0
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast lowercase__ : Optional[int] = datasets.utils.logging.get_logger(__name__) @dataclass class _UpperCAmelCase ( datasets.BuilderConfig): _lowerCAmelCase : int = 1_0_0_0_0 _lowerCAmelCase : Optional[List[str]] = None _lowerCAmelCase : Optional[datasets.Features] = None class _UpperCAmelCase ( datasets.ArrowBasedBuilder): _lowerCAmelCase : Dict = ParquetConfig def _snake_case ( self : List[Any] ): return datasets.DatasetInfo(features=self.config.features ) def _snake_case ( self : List[str] , lowercase_ : List[Any] ): if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}" ) snake_case_ : Union[str, Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(lowerCamelCase__ , (str, list, tuple) ): snake_case_ : List[str] = data_files if isinstance(lowerCamelCase__ , lowerCamelCase__ ): snake_case_ : Any = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive snake_case_ : Union[str, Any] = [dl_manager.iter_files(lowerCamelCase__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] snake_case_ : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): snake_case_ : int = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive snake_case_ : List[str] = [dl_manager.iter_files(lowerCamelCase__ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(lowerCamelCase__ ): with open(lowerCamelCase__ , '''rb''' ) as f: snake_case_ : int = datasets.Features.from_arrow_schema(pq.read_schema(lowerCamelCase__ ) ) break splits.append(datasets.SplitGenerator(name=lowerCamelCase__ , gen_kwargs={'''files''': files} ) ) return splits def _snake_case ( self : List[str] , lowercase_ : Optional[Any] ): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example snake_case_ : Tuple = table_cast(lowerCamelCase__ , self.info.features.arrow_schema ) return pa_table def _snake_case ( self : str , lowercase_ : str ): snake_case_ : Union[str, Any] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( f"Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(lowerCamelCase__ ) ): with open(lowerCamelCase__ , '''rb''' ) as f: snake_case_ : Union[str, Any] = pq.ParquetFile(lowerCamelCase__ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): snake_case_ : List[Any] = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", self._cast_table(lowerCamelCase__ ) except ValueError as e: logger.error(f"Failed to read file \'{file}\' with error {type(lowerCamelCase__ )}: {e}" ) raise
123
from typing import TYPE_CHECKING from ....utils import _LazyModule SCREAMING_SNAKE_CASE_:int = {"""tokenization_tapex""": ["""TapexTokenizer"""]} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys SCREAMING_SNAKE_CASE_:Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
662
0
import numpy as np import qiskit def _UpperCamelCase ( snake_case__ = 8, snake_case__ = None ) -> str: __UpperCAmelCase : Tuple = np.random.default_rng(seed=_lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. __UpperCAmelCase : List[Any] = 6 * key_len # Measurement basis for Alice's qubits. __UpperCAmelCase : List[str] = rng.integers(2, size=_lowerCAmelCase ) # The set of states Alice will prepare. __UpperCAmelCase : List[Any] = rng.integers(2, size=_lowerCAmelCase ) # Measurement basis for Bob's qubits. __UpperCAmelCase : Optional[Any] = rng.integers(2, size=_lowerCAmelCase ) # Quantum Circuit to simulate BB84 __UpperCAmelCase : List[Any] = qiskit.QuantumCircuit(_lowerCAmelCase, name="BB84" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(_lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(_lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(_lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. __UpperCAmelCase : int = qiskit.Aer.get_backend("aer_simulator" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. __UpperCAmelCase : Optional[Any] = qiskit.execute(_lowerCAmelCase, _lowerCAmelCase, shots=1, seed_simulator=_lowerCAmelCase ) # Returns the result of measurement. __UpperCAmelCase : Optional[int] = job.result().get_counts(_lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. __UpperCAmelCase : Any = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. __UpperCAmelCase : Union[str, Any] = gen_key[:key_len] if len(_lowerCAmelCase ) >= key_len else gen_key.ljust(_lowerCAmelCase, "0" ) return key if __name__ == "__main__": print(F'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
382
def __UpperCamelCase ( _lowerCAmelCase = 1000 ) -> int: """simple docstring""" A , A : str = 1, 1 A : List[Any] = [] for i in range(1 , n + 1 ): A : Optional[int] = prev_numerator + 2 * prev_denominator A : Any = prev_numerator + prev_denominator if len(str(_lowerCAmelCase ) ) > len(str(_lowerCAmelCase ) ): result.append(_lowerCAmelCase ) A : int = numerator A : int = denominator return len(_lowerCAmelCase ) if __name__ == "__main__": print(F"""{solution() = }""")
662
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ = logging.get_logger(__name__) a__ = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} a__ = { """vocab_file""": {"""mobilebert-uncased""": """https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt"""}, """tokenizer_file""": { """mobilebert-uncased""": """https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json""" }, } a__ = {"""mobilebert-uncased""": 5_1_2} a__ = {} class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : str = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : List[Any] = MobileBertTokenizer def __init__( self : int , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : List[Any]="[UNK]" , UpperCamelCase__ : Any="[SEP]" , UpperCamelCase__ : Tuple="[PAD]" , UpperCamelCase__ : Dict="[CLS]" , UpperCamelCase__ : str="[MASK]" , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : List[str]=None , **UpperCamelCase__ : int , ): '''simple docstring''' super().__init__( lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , do_lower_case=lowerCamelCase__ , unk_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , tokenize_chinese_chars=lowerCamelCase__ , strip_accents=lowerCamelCase__ , **lowerCamelCase__ , ) snake_case__ = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get("""lowercase""" , lowerCamelCase__) != do_lower_case or normalizer_state.get("""strip_accents""" , lowerCamelCase__) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowerCamelCase__) != tokenize_chinese_chars ): snake_case__ = getattr(lowerCamelCase__ , normalizer_state.pop("""type""")) snake_case__ = do_lower_case snake_case__ = strip_accents snake_case__ = tokenize_chinese_chars snake_case__ = normalizer_class(**lowerCamelCase__) snake_case__ = do_lower_case def __magic_name__ ( self : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any]=None): '''simple docstring''' snake_case__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __magic_name__ ( self : int , UpperCamelCase__ : Any , UpperCamelCase__ : str = None): '''simple docstring''' snake_case__ = [self.sep_token_id] snake_case__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def __magic_name__ ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[str, Any] = None): '''simple docstring''' snake_case__ = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__) return tuple(lowerCamelCase__)
654
import re def __UpperCamelCase ( _lowerCAmelCase ) -> str: """simple docstring""" if len(re.findall("""[ATCG]""" , _lowerCAmelCase ) ) != len(_lowerCAmelCase ): raise ValueError("""Invalid Strand""" ) return dna.translate(dna.maketrans("""ATCG""" , """TAGC""" ) ) if __name__ == "__main__": import doctest doctest.testmod()
662
0
from __future__ import annotations import time import numpy as np __A = [8, 5, 9, 7] __A = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] __A = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , ) ->Optional[int]: '''simple docstring''' lowerCamelCase__: str =claim_vector lowerCamelCase__: int =allocated_resources_table lowerCamelCase__: int =maximum_claim_table def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->int: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def SCREAMING_SNAKE_CASE_ (self : str) ->Any: '''simple docstring''' return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation()) def SCREAMING_SNAKE_CASE_ (self : str) ->int: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i]) - np.array(lowerCamelCase__)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' return {self.__need().index(lowerCamelCase__): i for i in self.__need()} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.__need() lowerCamelCase__: int =self.__allocated_resources_table lowerCamelCase__: Any =self.__available_resources() lowerCamelCase__: int =self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: lowerCamelCase__: Optional[Any] =False for each_need in need_list: lowerCamelCase__: Dict =True for index, need in enumerate(lowerCamelCase__): if need > available_resources[index]: lowerCamelCase__: List[Any] =False break if execution: lowerCamelCase__: Any =True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: lowerCamelCase__: int =original_need_index print(F"""Process {process_number + 1} is executing.""") # remove the process run from stack need_list.remove(lowerCamelCase__) # update available/freed resources stack lowerCamelCase__: Any =np.array(lowerCamelCase__) + np.array( alloc_resources_table[process_number]) print( "Updated available resource stack for processes: " + " ".join([str(lowerCamelCase__) for x in available_resources])) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def SCREAMING_SNAKE_CASE_ (self : str) ->Union[str, Any]: '''simple docstring''' print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(lowerCamelCase__) + 1}""" + " ".join(F"""{it:>8}""" for it in item) + "\n") print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( F"""P{self.__maximum_claim_table.index(lowerCamelCase__) + 1}""" + " ".join(F"""{it:>8}""" for it in item) + "\n") print( "Current Usage by Active Processes: " + " ".join(str(lowerCamelCase__) for x in self.__claim_vector)) print( "Initial Available Resources: " + " ".join(str(lowerCamelCase__) for x in self.__available_resources())) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
59
from __future__ import annotations SCREAMING_SNAKE_CASE_:Tuple = """#""" class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self ): A : dict = {} def _lowerCAmelCase ( self, lowerCamelCase__ ): A : List[Any] = self._trie for char in text: if char not in trie: A : str = {} A : str = trie[char] A : Optional[int] = True def _lowerCAmelCase ( self, lowerCamelCase__ ): A : Dict = self._trie for char in prefix: if char in trie: A : Optional[Any] = trie[char] else: return [] return self._elements(lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__ ): A : int = [] for c, v in d.items(): A : List[Any] = [""" """] if c == END else [(c + s) for s in self._elements(lowerCamelCase__ )] result.extend(lowerCamelCase__ ) return tuple(lowerCamelCase__ ) SCREAMING_SNAKE_CASE_:Any = Trie() SCREAMING_SNAKE_CASE_:Tuple = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def __UpperCamelCase ( _lowerCAmelCase ) -> tuple: """simple docstring""" A : List[str] = trie.find_word(_lowerCAmelCase ) return tuple(string + word for word in suffixes ) def __UpperCamelCase ( ) -> None: """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
662
0
'''simple docstring''' from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def __A ( lowerCamelCase_ = True , *lowerCamelCase_ , **lowerCamelCase_ ): """simple docstring""" if not is_tqdm_available(): raise ImportError("""Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = False if main_process_only: SCREAMING_SNAKE_CASE : int = PartialState().local_process_index == 0 return _tqdm(*_lowerCAmelCase , **_lowerCAmelCase , disable=_lowerCAmelCase )
379
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy SCREAMING_SNAKE_CASE_:Optional[int] = logging.getLogger(__name__) def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = False , ) -> Union[str, Any]: """simple docstring""" A : Optional[int] = bnb_quantization_config.load_in_abit A : int = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) A : Any = [] # custom device map if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and len(device_map.keys() ) > 1: A : Optional[int] = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: A : int = get_keys_to_not_convert(_lowerCAmelCase ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(_lowerCAmelCase ) A : Optional[Any] = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: A : Dict = [] A : Tuple = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(_lowerCAmelCase ) # compatibility with peft A : Union[str, Any] = load_in_abit A : Tuple = load_in_abit A : List[str] = get_parameter_device(_lowerCAmelCase ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) A : Optional[int] = replace_with_bnb_layers(_lowerCAmelCase , _lowerCAmelCase , modules_to_not_convert=_lowerCAmelCase ) # convert param to the right dtype A : Tuple = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: A : Optional[Any] = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) A : int = getattr(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(_lowerCAmelCase ): param.to(_lowerCAmelCase ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f'''The model device type is {model_device.type}. However, cuda is needed for quantization.''' """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f'''`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ''' ) else: with init_empty_weights(): A : str = replace_with_bnb_layers( _lowerCAmelCase , _lowerCAmelCase , modules_to_not_convert=_lowerCAmelCase ) A : Optional[Any] = get_quantized_model_device_map( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , max_memory=_lowerCAmelCase , no_split_module_classes=_lowerCAmelCase , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): A : Tuple = True A : int = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , dtype=bnb_quantization_config.torch_dtype , offload_folder=_lowerCAmelCase , offload_state_dict=_lowerCAmelCase , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(_lowerCAmelCase , device_map=_lowerCAmelCase , offload_dir=_lowerCAmelCase ) def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Optional[int]: """simple docstring""" if device_map is None: if torch.cuda.is_available(): A : Optional[int] = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) A : Tuple = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) A : Any = {} A : List[str] = special_dtypes A : Any = no_split_module_classes A : Union[str, Any] = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": A : Tuple = get_balanced_memory( _lowerCAmelCase , low_zero=(device_map == """balanced_low_0""") , max_memory=_lowerCAmelCase , **_lowerCAmelCase , ) A : int = max_memory A : Any = infer_auto_device_map(_lowerCAmelCase , **_lowerCAmelCase ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ): # check if don't have any quantized module on the cpu A : Optional[Any] = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules A : Optional[int] = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: A : Optional[Any] = [] A , A : Dict = _replace_with_bnb_layers( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , ) -> int: """simple docstring""" A : Optional[int] = False for name, module in model.named_children(): if current_key_name is None: A : int = [] current_key_name.append(_lowerCAmelCase ) if isinstance(_lowerCAmelCase , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` A : Dict = """.""".join(_lowerCAmelCase ) A : Optional[Any] = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: A : Dict = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: A : Optional[Any] = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_lowerCAmelCase , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: A : Dict = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) A : Any = module.weight.data if module.bias is not None: A : Any = module.bias.data bnb_module.requires_grad_(_lowerCAmelCase ) setattr(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) A : Dict = True if len(list(module.children() ) ) > 0: A , A : Dict = _replace_with_bnb_layers( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) A : Union[str, Any] = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def __UpperCamelCase ( _lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" with init_empty_weights(): A : Tuple = deepcopy(_lowerCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` A : Optional[int] = find_tied_parameters(_lowerCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A : int = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A : Optional[int] = sum(_lowerCAmelCase , [] ) A : Tuple = len(_lowerCAmelCase ) > 0 # Check if it is a base model A : List[str] = False if hasattr(_lowerCAmelCase , """base_model_prefix""" ): A : Optional[Any] = not hasattr(_lowerCAmelCase , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A : str = list(model.named_children() ) A : Tuple = [list_modules[-1][0]] # add last module together with tied weights A : int = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) A : Optional[Any] = list(set(_lowerCAmelCase ) ) + list(_lowerCAmelCase ) # remove ".weight" from the keys A : Union[str, Any] = [""".weight""", """.bias"""] A : Optional[int] = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A : List[str] = name.replace(_lowerCAmelCase , """""" ) filtered_module_names.append(_lowerCAmelCase ) return filtered_module_names def __UpperCamelCase ( _lowerCAmelCase ) -> Optional[int]: """simple docstring""" for m in model.modules(): if isinstance(_lowerCAmelCase , bnb.nn.Linearabit ): return True return False def __UpperCamelCase ( _lowerCAmelCase ) -> Optional[int]: """simple docstring""" return next(parameter.parameters() ).device def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(_lowerCAmelCase , _lowerCAmelCase , 0 , dtype=_lowerCAmelCase , value=_lowerCAmelCase ) A : Tuple = param_name A : Union[str, Any] = model if "." in tensor_name: A : int = tensor_name.split(""".""" ) for split in splits[:-1]: A : Union[str, Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ) if new_module is None: raise ValueError(f'''{module} has no attribute {split}.''' ) A : Optional[Any] = new_module A : List[str] = splits[-1] # offload weights A : Optional[int] = False offload_weight(module._parameters[tensor_name] , _lowerCAmelCase , _lowerCAmelCase , index=_lowerCAmelCase ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , _lowerCAmelCase , index=_lowerCAmelCase , ) else: offload_weight(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , index=_lowerCAmelCase ) offload_weight(_lowerCAmelCase , param_name.replace("""weight""" , """SCB""" ) , _lowerCAmelCase , index=_lowerCAmelCase ) set_module_tensor_to_device(_lowerCAmelCase , _lowerCAmelCase , """meta""" , dtype=_lowerCAmelCase , value=torch.empty(*param.size() ) )
662
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { """configuration_blenderbot_small""": [ """BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlenderbotSmallConfig""", """BlenderbotSmallOnnxConfig""", ], """tokenization_blenderbot_small""": ["""BlenderbotSmallTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ["""BlenderbotSmallTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ """BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlenderbotSmallForCausalLM""", """BlenderbotSmallForConditionalGeneration""", """BlenderbotSmallModel""", """BlenderbotSmallPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ """TFBlenderbotSmallForConditionalGeneration""", """TFBlenderbotSmallModel""", """TFBlenderbotSmallPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ """FlaxBlenderbotSmallForConditionalGeneration""", """FlaxBlenderbotSmallModel""", """FlaxBlenderbotSmallPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
232
from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from .run import RunCommand from .serving import ServeCommand from .user import UserCommands def __UpperCamelCase ( ) -> Dict: """simple docstring""" A : Tuple = ArgumentParser("""Transformers CLI tool""" , usage="""transformers-cli <command> [<args>]""" ) A : Dict = parser.add_subparsers(help="""transformers-cli command helpers""" ) # Register commands ConvertCommand.register_subcommand(_lowerCAmelCase ) DownloadCommand.register_subcommand(_lowerCAmelCase ) EnvironmentCommand.register_subcommand(_lowerCAmelCase ) RunCommand.register_subcommand(_lowerCAmelCase ) ServeCommand.register_subcommand(_lowerCAmelCase ) UserCommands.register_subcommand(_lowerCAmelCase ) AddNewModelCommand.register_subcommand(_lowerCAmelCase ) AddNewModelLikeCommand.register_subcommand(_lowerCAmelCase ) LfsCommands.register_subcommand(_lowerCAmelCase ) PTtoTFCommand.register_subcommand(_lowerCAmelCase ) # Let's go A : Tuple = parser.parse_args() if not hasattr(_lowerCAmelCase , """func""" ): parser.print_help() exit(1 ) # Run A : Any = args.func(_lowerCAmelCase ) service.run() if __name__ == "__main__": main()
662
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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 from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE_ : List[str] = { """configuration_xmod""": [ """XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XmodConfig""", """XmodOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ : Any = [ """XMOD_PRETRAINED_MODEL_ARCHIVE_LIST""", """XmodForCausalLM""", """XmodForMaskedLM""", """XmodForMultipleChoice""", """XmodForQuestionAnswering""", """XmodForSequenceClassification""", """XmodForTokenClassification""", """XmodModel""", """XmodPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
375
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_:int = { """configuration_blenderbot""": [ """BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlenderbotConfig""", """BlenderbotOnnxConfig""", ], """tokenization_blenderbot""": ["""BlenderbotTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Union[str, Any] = ["""BlenderbotTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Optional[int] = [ """BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlenderbotForCausalLM""", """BlenderbotForConditionalGeneration""", """BlenderbotModel""", """BlenderbotPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Union[str, Any] = [ """TFBlenderbotForConditionalGeneration""", """TFBlenderbotModel""", """TFBlenderbotPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Any = [ """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 SCREAMING_SNAKE_CASE_:Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
662
0
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __lowercase ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] = None , lowerCAmelCase__ : int = None , lowerCAmelCase__ : List[str] = False , **lowerCAmelCase__ : Union[str, Any] , ): super().__init__(features=lowerCamelCase__ , cache_dir=lowerCamelCase__ , keep_in_memory=lowerCamelCase__ , **lowerCamelCase__) SCREAMING_SNAKE_CASE_: int = Sql( cache_dir=lowerCamelCase__ , features=lowerCamelCase__ , sql=lowerCamelCase__ , con=lowerCamelCase__ , **lowerCamelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : List[str]): SCREAMING_SNAKE_CASE_: Any = None SCREAMING_SNAKE_CASE_: Optional[Any] = None SCREAMING_SNAKE_CASE_: Union[str, Any] = None SCREAMING_SNAKE_CASE_: Optional[Any] = None self.builder.download_and_prepare( download_config=lowerCamelCase__ , download_mode=lowerCamelCase__ , verification_mode=lowerCamelCase__ , base_path=lowerCamelCase__ , ) # Build dataset for splits SCREAMING_SNAKE_CASE_: List[Any] = self.builder.as_dataset( split="train" , verification_mode=lowerCamelCase__ , in_memory=self.keep_in_memory) return dataset class __lowercase : """simple docstring""" def __init__( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : str = None , lowerCAmelCase__ : int = None , **lowerCAmelCase__ : List[Any] , ): if num_proc is not None and num_proc <= 0: raise ValueError(F"num_proc {num_proc} must be an integer > 0.") SCREAMING_SNAKE_CASE_: List[Any] = dataset SCREAMING_SNAKE_CASE_: int = name SCREAMING_SNAKE_CASE_: str = con SCREAMING_SNAKE_CASE_: int = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE_: List[str] = num_proc SCREAMING_SNAKE_CASE_: str = to_sql_kwargs def _SCREAMING_SNAKE_CASE ( self : int): SCREAMING_SNAKE_CASE_: Dict = self.to_sql_kwargs.pop("sql" , lowerCamelCase__) SCREAMING_SNAKE_CASE_: Dict = self.to_sql_kwargs.pop("con" , lowerCamelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = self.to_sql_kwargs.pop("index" , lowerCamelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = self._write(index=lowerCamelCase__ , **self.to_sql_kwargs) return written def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : int): SCREAMING_SNAKE_CASE_: str = args SCREAMING_SNAKE_CASE_: Dict = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs SCREAMING_SNAKE_CASE_: Any = query_table( table=self.dataset.data , key=slice(lowerCamelCase__ , offset + self.batch_size) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE_: str = batch.to_pandas() SCREAMING_SNAKE_CASE_: Any = df.to_sql(self.name , self.con , index=lowerCamelCase__ , **lowerCamelCase__) return num_rows or len(lowerCamelCase__) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase__ : List[str] , **lowerCAmelCase__ : Dict): SCREAMING_SNAKE_CASE_: Dict = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset) , self.batch_size) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs)) else: SCREAMING_SNAKE_CASE_: str = len(self.dataset), self.batch_size with multiprocessing.Pool(self.num_proc) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , lowerCamelCase__ , lowerCamelCase__)] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
671
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> list[int]: """simple docstring""" A : Optional[int] = int(_lowerCAmelCase ) # Initialize Result A : int = [] # Traverse through all denomination for denomination in reversed(_lowerCAmelCase ): # Find denominations while int(_lowerCAmelCase ) >= int(_lowerCAmelCase ): total_value -= int(_lowerCAmelCase ) answer.append(_lowerCAmelCase ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": SCREAMING_SNAKE_CASE_:List[Any] = [] SCREAMING_SNAKE_CASE_:Dict = """0""" if ( input("""Do you want to enter your denominations ? (yY/n): """).strip().lower() == "y" ): SCREAMING_SNAKE_CASE_:Optional[int] = int(input("""Enter the number of denominations you want to add: """).strip()) for i in range(0, n): denominations.append(int(input(F"""Denomination {i}: """).strip())) SCREAMING_SNAKE_CASE_:Optional[Any] = input("""Enter the change you want to make in Indian Currency: """).strip() else: # All denominations of Indian Currency if user does not enter SCREAMING_SNAKE_CASE_:Tuple = [1, 2, 5, 10, 20, 50, 100, 500, 2_000] SCREAMING_SNAKE_CASE_:Optional[Any] = input("""Enter the change you want to make: """).strip() if int(value) == 0 or int(value) < 0: print("""The total value cannot be zero or negative.""") else: print(F"""Following is minimal change for {value}: """) SCREAMING_SNAKE_CASE_:str = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=""" """)
662
0
from math import factorial, pi def __lowercase ( _UpperCAmelCase , _UpperCAmelCase = 30 ) -> float: '''simple docstring''' if not isinstance(_lowerCAmelCase , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(_lowerCAmelCase , _lowerCAmelCase ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) __lowercase = float(_lowerCAmelCase ) __lowercase = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(_lowerCAmelCase ) ) def __lowercase ( _UpperCAmelCase , _UpperCAmelCase = 30 ) -> float: '''simple docstring''' if not isinstance(_lowerCAmelCase , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(_lowerCAmelCase , _lowerCAmelCase ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) __lowercase = float(_lowerCAmelCase ) __lowercase = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(_lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
321
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_:Union[str, Any] = """tiny-wmt19-en-ru""" # Build # borrowed from a test SCREAMING_SNAKE_CASE_:Union[str, Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE_:Any = dict(zip(vocab, range(len(vocab)))) SCREAMING_SNAKE_CASE_:Dict = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_:List[Any] = Path(tmpdirname) SCREAMING_SNAKE_CASE_:str = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] SCREAMING_SNAKE_CASE_:Union[str, Any] = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] SCREAMING_SNAKE_CASE_:Any = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) SCREAMING_SNAKE_CASE_:Optional[int] = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) SCREAMING_SNAKE_CASE_:Optional[int] = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) SCREAMING_SNAKE_CASE_:Optional[Any] = FSMTForConditionalGeneration(config) print(F"""num of params {tiny_model.num_parameters()}""") # Test SCREAMING_SNAKE_CASE_:Tuple = tokenizer(["""Making tiny model"""], return_tensors="""pt""") SCREAMING_SNAKE_CASE_:str = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"""Generated {mname_tiny}""") # Upload # transformers-cli upload tiny-wmt19-en-ru
662
0
def a__ ( _UpperCamelCase : Any ): if not all(char in '''01''' for char in bin_string ): raise ValueError('''Non-binary value was passed to the function''' ) if not bin_string: raise ValueError('''Empty string was passed to the function''' ) __lowerCamelCase = """""" while len(_lowerCAmelCase ) % 3 != 0: __lowerCamelCase = """0""" + bin_string __lowerCamelCase = [ bin_string[index : index + 3] for index in range(len(_lowerCAmelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: __lowerCamelCase = 0 for index, val in enumerate(_lowerCAmelCase ): oct_val += int(2 ** (2 - index) * int(_lowerCAmelCase ) ) oct_string += str(_lowerCAmelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
175
import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("""0.12.2"""): raise Exception("""requires fairseq >= 0.12.2""") if version.parse(fairseq.__version__) > version.parse("""2"""): raise Exception("""requires fairseq < v2""") logging.set_verbosity_info() SCREAMING_SNAKE_CASE_:Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_:int = """Hello, World!""" SCREAMING_SNAKE_CASE_:List[Any] = """en_XX""" def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Any: """simple docstring""" A : Optional[int] = Path("""data_bin""" ) A : Optional[Any] = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(_lowerCAmelCase ).parent ) , checkpoint_file=Path(_lowerCAmelCase ).name , _name="""xmod_base""" , arch="""xmod_base""" , task="""multilingual_masked_lm""" , data_name_or_path=str(_lowerCAmelCase ) , bpe="""sentencepiece""" , sentencepiece_model=str(Path(_lowerCAmelCase ).parent / """sentencepiece.bpe.model""" ) , src_dict=str(data_dir / """dict.txt""" ) , ) xmod.eval() # disable dropout print(_lowerCAmelCase ) A : Any = xmod.model.encoder.sentence_encoder A : Optional[int] = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , """bottleneck""" , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: A : List[str] = xmod.model.classification_heads["""mnli"""].out_proj.weight.shape[0] print("""Our X-MOD config:""" , _lowerCAmelCase ) A : int = XmodForSequenceClassification(_lowerCAmelCase ) if classification_head else XmodForMaskedLM(_lowerCAmelCase ) model.eval() # Now let's copy all the weights. # Embeddings A : Any = xmod_sent_encoder.embed_tokens.weight A : int = xmod_sent_encoder.embed_positions.weight A : str = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. A : Dict = xmod_sent_encoder.layernorm_embedding.weight A : int = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer A : str = model.roberta.encoder.layer[i] A : Tuple = xmod_sent_encoder.layers[i] # self attention A : Optional[int] = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError("""Dimensions of self-attention weights do not match.""" ) A : List[str] = xmod_layer.self_attn.q_proj.weight A : Optional[int] = xmod_layer.self_attn.q_proj.bias A : List[Any] = xmod_layer.self_attn.k_proj.weight A : Union[str, Any] = xmod_layer.self_attn.k_proj.bias A : Optional[int] = xmod_layer.self_attn.v_proj.weight A : Dict = xmod_layer.self_attn.v_proj.bias # self-attention output A : Optional[Any] = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError("""Dimensions of self-attention output weights do not match.""" ) A : Optional[Any] = xmod_layer.self_attn.out_proj.weight A : Dict = xmod_layer.self_attn.out_proj.bias A : Union[str, Any] = xmod_layer.self_attn_layer_norm.weight A : str = xmod_layer.self_attn_layer_norm.bias # intermediate A : str = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError("""Dimensions of intermediate weights do not match.""" ) A : Optional[int] = xmod_layer.fca.weight A : Optional[int] = xmod_layer.fca.bias # output A : Dict = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError("""Dimensions of feed-forward weights do not match.""" ) A : Union[str, Any] = xmod_layer.fca.weight A : int = xmod_layer.fca.bias A : List[str] = xmod_layer.final_layer_norm.weight A : Optional[Any] = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: A : str = xmod_layer.adapter_layer_norm.weight A : str = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError("""Lists of language adapters do not match.""" ) for lang_code, adapter in xmod_layer.adapter_modules.items(): A : Optional[int] = bert_output.adapter_modules[lang_code] A : int = xmod_layer.adapter_modules[lang_code] A : Optional[Any] = from_adapter.fca.weight A : Optional[Any] = from_adapter.fca.bias A : List[str] = from_adapter.fca.weight A : Any = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: A : Dict = xmod_sent_encoder.layer_norm.weight A : int = xmod_sent_encoder.layer_norm.bias if classification_head: A : int = xmod.model.classification_heads["""mnli"""].dense.weight A : Optional[Any] = xmod.model.classification_heads["""mnli"""].dense.bias A : List[str] = xmod.model.classification_heads["""mnli"""].out_proj.weight A : List[str] = xmod.model.classification_heads["""mnli"""].out_proj.bias else: # LM Head A : Any = xmod.model.encoder.lm_head.dense.weight A : Tuple = xmod.model.encoder.lm_head.dense.bias A : Any = xmod.model.encoder.lm_head.layer_norm.weight A : List[str] = xmod.model.encoder.lm_head.layer_norm.bias A : Union[str, Any] = xmod.model.encoder.lm_head.weight A : Tuple = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. A : Optional[int] = xmod.encode(_lowerCAmelCase ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(_lowerCAmelCase ) A : List[str] = model(_lowerCAmelCase )[0] if classification_head: A : Dict = xmod.model.classification_heads["""mnli"""](xmod.extract_features(_lowerCAmelCase ) ) else: A : Optional[Any] = xmod.model(_lowerCAmelCase , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) A : str = torch.max(torch.abs(our_output - their_output ) ).item() print(f'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 A : Optional[Any] = torch.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=1e-3 ) print("""Do both models output the same tensors?""" , """🔥""" if success else """💩""" ) if not success: raise Exception("""Something went wRoNg""" ) Path(_lowerCAmelCase ).mkdir(parents=_lowerCAmelCase , exist_ok=_lowerCAmelCase ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_:Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--xmod_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.""" ) parser.add_argument( """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head.""" ) SCREAMING_SNAKE_CASE_:Optional[Any] = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
662
0
import torch def SCREAMING_SNAKE_CASE ( ) -> Dict: if torch.cuda.is_available(): lowerCamelCase__ : str = torch.cuda.device_count() else: lowerCamelCase__ : Optional[Any] = 0 print(F"""Successfully ran on {num_gpus} GPUs""" ) if __name__ == "__main__": main()
295
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase ( self ): A : Any = tempfile.mkdtemp() A : List[str] = BlipImageProcessor() A : Union[str, Any] = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) A : str = BlipProcessor(lowerCamelCase__, lowerCamelCase__ ) processor.save_pretrained(self.tmpdirname ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): return AutoProcessor.from_pretrained(self.tmpdirname, **lowerCamelCase__ ).tokenizer def _lowerCAmelCase ( self, **lowerCamelCase__ ): return AutoProcessor.from_pretrained(self.tmpdirname, **lowerCamelCase__ ).image_processor def _lowerCAmelCase ( self ): shutil.rmtree(self.tmpdirname ) def _lowerCAmelCase ( self ): A : Any = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta )] A : Any = [Image.fromarray(np.moveaxis(lowerCamelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs def _lowerCAmelCase ( self ): A : int = BlipProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Any = self.get_tokenizer(bos_token="""(BOS)""", eos_token="""(EOS)""" ) A : Union[str, Any] = self.get_image_processor(do_normalize=lowerCamelCase__, padding_value=1.0 ) A : Dict = BlipProcessor.from_pretrained( self.tmpdirname, bos_token="""(BOS)""", eos_token="""(EOS)""", do_normalize=lowerCamelCase__, padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer, lowerCamelCase__ ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : Optional[int] = self.get_image_processor() A : str = self.get_tokenizer() A : Dict = BlipProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Any = self.prepare_image_inputs() A : int = image_processor(lowerCamelCase__, return_tensors="""np""" ) A : Optional[Any] = processor(images=lowerCamelCase__, return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2 ) def _lowerCAmelCase ( self ): A : List[str] = self.get_image_processor() A : int = self.get_tokenizer() A : str = BlipProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Optional[Any] = """lower newer""" A : List[Any] = processor(text=lowerCamelCase__ ) A : str = tokenizer(lowerCamelCase__, return_token_type_ids=lowerCamelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key], encoded_processor[key] ) def _lowerCAmelCase ( self ): A : List[Any] = self.get_image_processor() A : Dict = self.get_tokenizer() A : Union[str, Any] = BlipProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Optional[int] = """lower newer""" A : Union[str, Any] = self.prepare_image_inputs() A : str = processor(text=lowerCamelCase__, images=lowerCamelCase__ ) self.assertListEqual(list(inputs.keys() ), ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase__ ): processor() def _lowerCAmelCase ( self ): A : List[Any] = self.get_image_processor() A : Dict = self.get_tokenizer() A : Dict = BlipProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A : Optional[int] = processor.batch_decode(lowerCamelCase__ ) A : Dict = tokenizer.batch_decode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : Optional[int] = self.get_image_processor() A : int = self.get_tokenizer() A : Optional[int] = BlipProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Optional[int] = """lower newer""" A : List[str] = self.prepare_image_inputs() A : Optional[int] = processor(text=lowerCamelCase__, images=lowerCamelCase__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ), ["""pixel_values""", """input_ids""", """attention_mask"""] )
662
0
"""simple docstring""" import copy import re class _UpperCAmelCase : _lowerCAmelCase : Any = "hp" _lowerCAmelCase : Dict = {} _lowerCAmelCase : Optional[Any] = None @classmethod def _snake_case ( cls : str , lowercase_ : List[Any] , lowercase_ : str ): snake_case_ : Union[str, Any] = prefix snake_case_ : Optional[Any] = defaults cls.build_naming_info() @staticmethod def _snake_case ( lowercase_ : List[Any] , lowercase_ : Optional[int] ): if len(lowerCamelCase__ ) == 0: return "" snake_case_ : Union[str, Any] = None if any(char.isdigit() for char in word ): raise Exception(f"Parameters should not contain numbers: \'{word}\' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(lowerCamelCase__ ) + 1 ): snake_case_ : Union[str, Any] = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: snake_case_ : str = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(lowercase_ : str ): snake_case_ : Any = """""" while integer != 0: snake_case_ : Dict = chr(ord('''A''' ) + integer % 10 ) + s integer //= 10 return s snake_case_ : str = 0 while True: snake_case_ : Union[str, Any] = word + """#""" + int_to_alphabetic(lowerCamelCase__ ) if sword in info["reverse_short_word"]: continue else: snake_case_ : Union[str, Any] = sword break snake_case_ : Any = short_word snake_case_ : Optional[int] = word return short_word @staticmethod def _snake_case ( lowercase_ : Union[str, Any] , lowercase_ : List[str] ): snake_case_ : Union[str, Any] = param_name.split('''_''' ) snake_case_ : Optional[Any] = [TrialShortNamer.shortname_for_word(lowerCamelCase__ , lowerCamelCase__ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name snake_case_ : Any = ["""""", """_"""] for separator in separators: snake_case_ : Optional[Any] = separator.join(lowerCamelCase__ ) if shortname not in info["reverse_short_param"]: snake_case_ : str = shortname snake_case_ : List[str] = param_name return shortname return param_name @staticmethod def _snake_case ( lowercase_ : Tuple , lowercase_ : str ): snake_case_ : Any = TrialShortNamer.shortname_for_key(lowerCamelCase__ , lowerCamelCase__ ) snake_case_ : Dict = short_name snake_case_ : Tuple = param_name @classmethod def _snake_case ( cls : Dict ): if cls.NAMING_INFO is not None: return snake_case_ : Tuple = { """short_word""": {}, """reverse_short_word""": {}, """short_param""": {}, """reverse_short_param""": {}, } snake_case_ : int = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(lowerCamelCase__ , lowerCamelCase__ ) snake_case_ : Optional[Any] = info @classmethod def _snake_case ( cls : str , lowercase_ : Optional[Any] ): cls.build_naming_info() assert cls.PREFIX is not None snake_case_ : List[Any] = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue snake_case_ : Optional[Any] = cls.NAMING_INFO["""short_param"""][k] if isinstance(lowerCamelCase__ , lowerCamelCase__ ): snake_case_ : Tuple = 1 if v else 0 snake_case_ : Union[str, Any] = """""" if isinstance(lowerCamelCase__ , (int, float) ) else """-""" snake_case_ : Any = f"{key}{sep}{v}" name.append(lowerCamelCase__ ) return "_".join(lowerCamelCase__ ) @classmethod def _snake_case ( cls : Tuple , lowercase_ : Dict ): snake_case_ : Optional[Any] = repr[len(cls.PREFIX ) + 1 :] if repr == "": snake_case_ : List[str] = [] else: snake_case_ : List[str] = repr.split('''_''' ) snake_case_ : Union[str, Any] = {} for value in values: if "-" in value: snake_case_ : Optional[Any] = value.split('''-''' ) else: snake_case_ : Any = re.sub('''[0-9.]''' , '''''' , lowerCamelCase__ ) snake_case_ : Dict = float(re.sub('''[^0-9.]''' , '''''' , lowerCamelCase__ ) ) snake_case_ : Optional[Any] = cls.NAMING_INFO["""reverse_short_param"""][p_k] snake_case_ : int = p_v for k in cls.DEFAULTS: if k not in parameters: snake_case_ : Any = cls.DEFAULTS[k] return parameters
123
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__ ): return f'''gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase__ ) for s in shape] )}.npy''' def _lowerCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def _lowerCAmelCase ( self, lowerCamelCase__=0, lowerCamelCase__=(4, 4, 64, 64), lowerCamelCase__=False ): A : Optional[Any] = jnp.bfloataa if fpaa else jnp.floataa A : Union[str, Any] = jnp.array(load_hf_numpy(self.get_file_format(lowerCamelCase__, lowerCamelCase__ ) ), dtype=lowerCamelCase__ ) return image def _lowerCAmelCase ( self, lowerCamelCase__=False, lowerCamelCase__="CompVis/stable-diffusion-v1-4" ): A : str = jnp.bfloataa if fpaa else jnp.floataa A : Union[str, Any] = """bf16""" if fpaa else None A , A : str = FlaxUNetaDConditionModel.from_pretrained( lowerCamelCase__, subfolder="""unet""", dtype=lowerCamelCase__, revision=lowerCamelCase__ ) return model, params def _lowerCAmelCase ( self, lowerCamelCase__=0, lowerCamelCase__=(4, 77, 768), lowerCamelCase__=False ): A : Optional[int] = jnp.bfloataa if fpaa else jnp.floataa A : List[str] = jnp.array(load_hf_numpy(self.get_file_format(lowerCamelCase__, lowerCamelCase__ ) ), dtype=lowerCamelCase__ ) return hidden_states @parameterized.expand( [ # fmt: off [83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]], [17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]], [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]], [3, 1000, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]], # fmt: on ] ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ): A , A : List[str] = self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""", fpaa=lowerCamelCase__ ) A : str = self.get_latents(lowerCamelCase__, fpaa=lowerCamelCase__ ) A : int = self.get_encoder_hidden_states(lowerCamelCase__, fpaa=lowerCamelCase__ ) A : Optional[Any] = model.apply( {"""params""": params}, lowerCamelCase__, jnp.array(lowerCamelCase__, dtype=jnp.intaa ), encoder_hidden_states=lowerCamelCase__, ).sample assert sample.shape == latents.shape A : int = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ), dtype=jnp.floataa ) A : Dict = jnp.array(lowerCamelCase__, dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(lowerCamelCase__, lowerCamelCase__, atol=1e-2 ) @parameterized.expand( [ # fmt: off [83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]], [17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]], [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]], [3, 1000, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]], # fmt: on ] ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ): A , A : Tuple = self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""", fpaa=lowerCamelCase__ ) A : int = self.get_latents(lowerCamelCase__, shape=(4, 4, 96, 96), fpaa=lowerCamelCase__ ) A : Union[str, Any] = self.get_encoder_hidden_states(lowerCamelCase__, shape=(4, 77, 1024), fpaa=lowerCamelCase__ ) A : Dict = model.apply( {"""params""": params}, lowerCamelCase__, jnp.array(lowerCamelCase__, dtype=jnp.intaa ), encoder_hidden_states=lowerCamelCase__, ).sample assert sample.shape == latents.shape A : Dict = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ), dtype=jnp.floataa ) A : List[Any] = jnp.array(lowerCamelCase__, dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(lowerCamelCase__, lowerCamelCase__, atol=1e-2 )
662
0
def _UpperCamelCase ( snake_case__, snake_case__ ) -> int: return 1 if input_a == input_a else 0 def _UpperCamelCase ( ) -> None: assert xnor_gate(0, 0 ) == 1 assert xnor_gate(0, 1 ) == 0 assert xnor_gate(1, 0 ) == 0 assert xnor_gate(1, 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
382
from typing import Any import numpy as np def __UpperCamelCase ( _lowerCAmelCase ) -> bool: """simple docstring""" return np.array_equal(_lowerCAmelCase , matrix.conjugate().T ) def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: """simple docstring""" A : Any = v.conjugate().T A : List[Any] = v_star.dot(_lowerCAmelCase ) assert isinstance(_lowerCAmelCase , np.ndarray ) return (v_star_dot.dot(_lowerCAmelCase )) / (v_star.dot(_lowerCAmelCase )) def __UpperCamelCase ( ) -> None: """simple docstring""" A : Any = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) A : str = np.array([[1], [2], [3]] ) assert is_hermitian(_lowerCAmelCase ), f'''{a} is not hermitian.''' print(rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) ) A : Tuple = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(_lowerCAmelCase ), f'''{a} is not hermitian.''' assert rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
662
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a__ = logging.get_logger(__name__) a__ = { """google/bit-50""": """https://huggingface.co/google/bit-50/resolve/main/config.json""", } class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowercase : Optional[Any] = "bit" _lowercase : Union[str, Any] = ["preactivation", "bottleneck"] _lowercase : Union[str, Any] = ["SAME", "VALID"] def __init__( self : List[str] , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Dict=6_4 , UpperCamelCase__ : Optional[Any]=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , UpperCamelCase__ : Dict=[3, 4, 6, 3] , UpperCamelCase__ : Optional[Any]="preactivation" , UpperCamelCase__ : Any="relu" , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Union[str, Any]=3_2 , UpperCamelCase__ : Union[str, Any]=0.0 , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : int=3_2 , UpperCamelCase__ : List[Any]=1 , UpperCamelCase__ : int=None , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : int , ): '''simple docstring''' super().__init__(**lowerCamelCase__) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {','.join(self.layer_types)}''') if global_padding is not None: if global_padding.upper() in self.supported_padding: snake_case__ = global_padding.upper() else: raise ValueError(F'''Padding strategy {global_padding} not supported''') snake_case__ = num_channels snake_case__ = embedding_size snake_case__ = hidden_sizes snake_case__ = depths snake_case__ = layer_type snake_case__ = hidden_act snake_case__ = global_padding snake_case__ = num_groups snake_case__ = drop_path_rate snake_case__ = embedding_dynamic_padding snake_case__ = output_stride snake_case__ = width_factor snake_case__ = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 , len(lowerCamelCase__) + 1)] snake_case__ = get_aligned_output_features_output_indices( out_features=lowerCamelCase__ , out_indices=lowerCamelCase__ , stage_names=self.stage_names)
654
from __future__ import annotations import numpy as np def __UpperCamelCase ( _lowerCAmelCase ) -> tuple[np.ndarray, np.ndarray]: """simple docstring""" A , A : int = np.shape(_lowerCAmelCase ) if rows != columns: A : Union[str, Any] = ( """'table' has to be of square shaped array but got a """ f'''{rows}x{columns} array:\n{table}''' ) raise ValueError(_lowerCAmelCase ) A : Union[str, Any] = np.zeros((rows, columns) ) A : Dict = np.zeros((rows, columns) ) for i in range(_lowerCAmelCase ): for j in range(_lowerCAmelCase ): A : Any = sum(lower[i][k] * upper[k][j] for k in range(_lowerCAmelCase ) ) if upper[j][j] == 0: raise ArithmeticError("""No LU decomposition exists""" ) A : Any = (table[i][j] - total) / upper[j][j] A : Union[str, Any] = 1 for j in range(_lowerCAmelCase , _lowerCAmelCase ): A : Any = sum(lower[i][k] * upper[k][j] for k in range(_lowerCAmelCase ) ) A : str = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
662
0
import tensorflow as tf from ...tf_utils import shape_list class lowerCamelCase (tf.keras.layers.Layer ): """simple docstring""" def __init__( self : str, _UpperCAmelCase : List[Any], _UpperCAmelCase : List[str], _UpperCAmelCase : Optional[int], _UpperCAmelCase : List[Any], _UpperCAmelCase : List[Any]=1, _UpperCAmelCase : List[str]=False, **_UpperCAmelCase : Optional[Any] ) -> Optional[int]: """simple docstring""" super().__init__(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Dict = d_embed SCREAMING_SNAKE_CASE__ : Optional[int] = d_proj SCREAMING_SNAKE_CASE__ : List[Any] = cutoffs + [vocab_size] SCREAMING_SNAKE_CASE__ : int = [0] + self.cutoffs SCREAMING_SNAKE_CASE__ : Tuple = div_val SCREAMING_SNAKE_CASE__ : List[Any] = self.cutoffs[0] SCREAMING_SNAKE_CASE__ : int = len(self.cutoffs ) - 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.shortlist_size + self.n_clusters SCREAMING_SNAKE_CASE__ : str = keep_order SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] def A_ ( self : Dict, _UpperCAmelCase : Any ) -> Union[str, Any]: """simple docstring""" if self.n_clusters > 0: SCREAMING_SNAKE_CASE__ : str = self.add_weight( shape=(self.n_clusters, self.d_embed), initializer="zeros", trainable=_UpperCAmelCase, name="cluster_weight" ) SCREAMING_SNAKE_CASE__ : int = self.add_weight( shape=(self.n_clusters,), initializer="zeros", trainable=_UpperCAmelCase, name="cluster_bias" ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: SCREAMING_SNAKE_CASE__ : List[str] = self.add_weight( shape=(self.d_embed, self.d_proj), initializer="zeros", trainable=_UpperCAmelCase, name=F'''out_projs_._{i}''', ) self.out_projs.append(_UpperCAmelCase ) else: self.out_projs.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.add_weight( shape=(self.vocab_size, self.d_embed), initializer="zeros", trainable=_UpperCAmelCase, name=F'''out_layers_._{i}_._weight''', ) SCREAMING_SNAKE_CASE__ : List[Any] = self.add_weight( shape=(self.vocab_size,), initializer="zeros", trainable=_UpperCAmelCase, name=F'''out_layers_._{i}_._bias''', ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = self.cutoff_ends[i], self.cutoff_ends[i + 1] SCREAMING_SNAKE_CASE__ : Dict = self.d_embed // (self.div_val**i) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.add_weight( shape=(d_emb_i, self.d_proj), initializer="zeros", trainable=_UpperCAmelCase, name=F'''out_projs_._{i}''' ) self.out_projs.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.add_weight( shape=(r_idx - l_idx, d_emb_i), initializer="zeros", trainable=_UpperCAmelCase, name=F'''out_layers_._{i}_._weight''', ) SCREAMING_SNAKE_CASE__ : Any = self.add_weight( shape=(r_idx - l_idx,), initializer="zeros", trainable=_UpperCAmelCase, name=F'''out_layers_._{i}_._bias''', ) self.out_layers.append((weight, bias) ) super().build(_UpperCAmelCase ) @staticmethod def A_ ( _UpperCAmelCase : int, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any, _UpperCAmelCase : Optional[Any]=None ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = x if proj is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = tf.einsum("ibd,ed->ibe", _UpperCAmelCase, _UpperCAmelCase ) return tf.einsum("ibd,nd->ibn", _UpperCAmelCase, _UpperCAmelCase ) + b @staticmethod def A_ ( _UpperCAmelCase : Dict, _UpperCAmelCase : Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = shape_list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tf.range(lp_size[0], dtype=target.dtype ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.stack([r, target], 1 ) return tf.gather_nd(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : str, _UpperCAmelCase : Dict, _UpperCAmelCase : Any, _UpperCAmelCase : str=True, _UpperCAmelCase : Optional[int]=False ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 0 if self.n_clusters == 0: SCREAMING_SNAKE_CASE__ : Dict = self._logit(_UpperCAmelCase, self.out_layers[0][0], self.out_layers[0][1], self.out_projs[0] ) if target is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=_UpperCAmelCase, logits=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = tf.nn.log_softmax(_UpperCAmelCase, axis=-1 ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = shape_list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Any = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: SCREAMING_SNAKE_CASE__ : int = (target >= l_idx) & (target < r_idx) SCREAMING_SNAKE_CASE__ : List[Any] = tf.where(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.boolean_mask(_UpperCAmelCase, _UpperCAmelCase ) - l_idx if self.div_val == 1: SCREAMING_SNAKE_CASE__ : Dict = self.out_layers[0][0][l_idx:r_idx] SCREAMING_SNAKE_CASE__ : Optional[int] = self.out_layers[0][1][l_idx:r_idx] else: SCREAMING_SNAKE_CASE__ : Optional[int] = self.out_layers[i][0] SCREAMING_SNAKE_CASE__ : Dict = self.out_layers[i][1] if i == 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.concat([cur_W, self.cluster_weight], 0 ) SCREAMING_SNAKE_CASE__ : str = tf.concat([cur_b, self.cluster_bias], 0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._logit(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, self.out_projs[0] ) SCREAMING_SNAKE_CASE__ : str = tf.nn.log_softmax(_UpperCAmelCase ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: SCREAMING_SNAKE_CASE__ : Tuple = tf.boolean_mask(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = self._gather_logprob(_UpperCAmelCase, _UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : int = self._logit(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, self.out_projs[i] ) SCREAMING_SNAKE_CASE__ : Tuple = tf.nn.log_softmax(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self.cutoffs[0] + i - 1 # No probability for the head cluster SCREAMING_SNAKE_CASE__ : Optional[int] = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(_UpperCAmelCase ) if target is not None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.boolean_mask(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tf.boolean_mask(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self._gather_logprob(_UpperCAmelCase, _UpperCAmelCase ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(_UpperCAmelCase, -cur_logprob, shape_list(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat(_UpperCAmelCase, axis=-1 ) if target is not None: if return_mean: SCREAMING_SNAKE_CASE__ : List[str] = tf.reduce_mean(_UpperCAmelCase ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(_UpperCAmelCase ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(_UpperCAmelCase, name=self.name, aggregation="mean" if return_mean else "" ) return out
663
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase : List[str] = 2_0_0 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase : Any = 5_0 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase : str = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1_0_0_0)) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, float]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = len([g for position, g in enumerate(SCREAMING_SNAKE_CASE__ ) if g == main_target[position]] ) return (item, float(SCREAMING_SNAKE_CASE__ )) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) SCREAMING_SNAKE_CASE__ : Tuple = parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE__ : str = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = list(SCREAMING_SNAKE_CASE__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE__ : Tuple = random.choice(SCREAMING_SNAKE_CASE__ ) return "".join(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : tuple[str, float] , SCREAMING_SNAKE_CASE__ : list[tuple[str, float]] , SCREAMING_SNAKE_CASE__ : list[str] , ) -> list[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE__ : List[str] = int(parent_a[1] * 1_00 ) + 1 SCREAMING_SNAKE_CASE__ : Tuple = 10 if child_n >= 10 else child_n for _ in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = population_score[random.randint(0 , SCREAMING_SNAKE_CASE__ )][0] SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = crossover(parent_a[0] , SCREAMING_SNAKE_CASE__ ) # Append new string to the population list. pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) return pop def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] , SCREAMING_SNAKE_CASE__ : bool = True ) -> tuple[int, int, str]: '''simple docstring''' if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE__ : str = f'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE__ : Optional[int] = sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE__ : Dict = f'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Generate random starting population. SCREAMING_SNAKE_CASE__ : List[Any] = [] for _ in range(SCREAMING_SNAKE_CASE__ ): population.append("".join([random.choice(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(SCREAMING_SNAKE_CASE__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE__ : int = [evaluate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE__ : List[str] = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[1] , reverse=SCREAMING_SNAKE_CASE__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f'''\nGeneration: {generation}''' f'''\nTotal Population:{total_population}''' f'''\nBest score: {population_score[0][1]}''' f'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE__ : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(SCREAMING_SNAKE_CASE__ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ (item, score / len(SCREAMING_SNAKE_CASE__ )) for item, score in population_score ] # This is selection for i in range(SCREAMING_SNAKE_CASE__ ): population.extend(select(population_score[int(SCREAMING_SNAKE_CASE__ )] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(SCREAMING_SNAKE_CASE__ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase : Dict = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) _lowerCamelCase : Tuple = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = basic(target_str, genes_list) print( f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
663
1
from collections.abc import Callable import numpy as np def _a ( SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = int(np.ceil((x_end - xa) / step_size ) ) SCREAMING_SNAKE_CASE__ : Tuple = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE__ : Tuple = ya SCREAMING_SNAKE_CASE__ : Dict = xa for k in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = y[k] + step_size * ode_func(SCREAMING_SNAKE_CASE__ , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
663
from collections.abc import Callable import numpy as np def _a ( SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = int(np.ceil((x_end - xa) / step_size ) ) SCREAMING_SNAKE_CASE__ : Tuple = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE__ : Tuple = ya SCREAMING_SNAKE_CASE__ : Dict = xa for k in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = y[k] + step_size * ode_func(SCREAMING_SNAKE_CASE__ , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
663
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : List[str] = { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json''' ), '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json''', '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json''', '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json''', '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json''', # See all REALM models at https://huggingface.co/models?filter=realm } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "realm" def __init__( self : List[Any], _UpperCAmelCase : str=3_0_5_2_2, _UpperCAmelCase : Tuple=7_6_8, _UpperCAmelCase : int=1_2_8, _UpperCAmelCase : Any=1_2, _UpperCAmelCase : Tuple=1_2, _UpperCAmelCase : int=8, _UpperCAmelCase : Tuple=3_0_7_2, _UpperCAmelCase : List[Any]="gelu_new", _UpperCAmelCase : Any=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : List[str]=5_1_2, _UpperCAmelCase : Optional[int]=2, _UpperCAmelCase : Optional[Any]=0.02, _UpperCAmelCase : Dict=1E-12, _UpperCAmelCase : List[str]=2_5_6, _UpperCAmelCase : Dict=1_0, _UpperCAmelCase : Optional[Any]=1E-3, _UpperCAmelCase : Union[str, Any]=5, _UpperCAmelCase : int=3_2_0, _UpperCAmelCase : List[Any]=1_3_3_5_3_7_1_8, _UpperCAmelCase : Tuple=5_0_0_0, _UpperCAmelCase : List[Any]=1, _UpperCAmelCase : Optional[int]=0, _UpperCAmelCase : Union[str, Any]=2, **_UpperCAmelCase : int, ) -> Optional[Any]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase, bos_token_id=_UpperCAmelCase, eos_token_id=_UpperCAmelCase, **_UpperCAmelCase ) # Common config SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : int = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Any = retriever_proj_size SCREAMING_SNAKE_CASE__ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : str = num_candidates SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps # Reader config SCREAMING_SNAKE_CASE__ : Optional[Any] = span_hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_span_width SCREAMING_SNAKE_CASE__ : str = reader_layer_norm_eps SCREAMING_SNAKE_CASE__ : int = reader_beam_size SCREAMING_SNAKE_CASE__ : int = reader_seq_len # Retrieval config SCREAMING_SNAKE_CASE__ : Dict = num_block_records SCREAMING_SNAKE_CASE__ : List[Any] = searcher_beam_size
663
def _a ( SCREAMING_SNAKE_CASE__ : List[Any]=2_81_23 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i SCREAMING_SNAKE_CASE__ : int = set() SCREAMING_SNAKE_CASE__ : Any = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(SCREAMING_SNAKE_CASE__ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
663
1
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging _lowerCamelCase : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCamelCase (__lowerCamelCase ): """simple docstring""" def __init__( self : Tuple, _UpperCAmelCase : CLIPSegForImageSegmentation, _UpperCAmelCase : CLIPSegProcessor, _UpperCAmelCase : AutoencoderKL, _UpperCAmelCase : CLIPTextModel, _UpperCAmelCase : CLIPTokenizer, _UpperCAmelCase : UNetaDConditionModel, _UpperCAmelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler], _UpperCAmelCase : StableDiffusionSafetyChecker, _UpperCAmelCase : CLIPImageProcessor, ) -> Union[str, Any]: """simple docstring""" super().__init__() if hasattr(scheduler.config, "steps_offset" ) and scheduler.config.steps_offset != 1: SCREAMING_SNAKE_CASE__ : int = ( F'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' F''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1", "1.0.0", _UpperCAmelCase, standard_warn=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dict(scheduler.config ) SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : str = FrozenDict(_UpperCAmelCase ) if hasattr(scheduler.config, "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: SCREAMING_SNAKE_CASE__ : List[str] = ( F'''The configuration file of this scheduler: {scheduler} has not set the configuration''' " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set", "1.0.0", _UpperCAmelCase, standard_warn=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = dict(scheduler.config ) SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : str = FrozenDict(_UpperCAmelCase ) if safety_checker is None: logger.warning( F'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=_UpperCAmelCase, segmentation_processor=_UpperCAmelCase, vae=_UpperCAmelCase, text_encoder=_UpperCAmelCase, tokenizer=_UpperCAmelCase, unet=_UpperCAmelCase, scheduler=_UpperCAmelCase, safety_checker=_UpperCAmelCase, feature_extractor=_UpperCAmelCase, ) def A_ ( self : Optional[int], _UpperCAmelCase : Optional[Union[str, int]] = "auto" ) -> List[Any]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE__ : Dict = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_UpperCAmelCase ) def A_ ( self : List[Any] ) -> int: """simple docstring""" self.enable_attention_slicing(_UpperCAmelCase ) def A_ ( self : Any ) -> List[str]: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_UpperCAmelCase, _UpperCAmelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def A_ ( self : str ) -> List[Any]: """simple docstring""" if self.device != torch.device("meta" ) or not hasattr(self.unet, "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(_UpperCAmelCase, "_hf_hook" ) and hasattr(module._hf_hook, "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : List[Any], _UpperCAmelCase : Union[str, List[str]], _UpperCAmelCase : Union[torch.FloatTensor, PIL.Image.Image], _UpperCAmelCase : str, _UpperCAmelCase : int = 5_1_2, _UpperCAmelCase : int = 5_1_2, _UpperCAmelCase : int = 5_0, _UpperCAmelCase : float = 7.5, _UpperCAmelCase : Optional[Union[str, List[str]]] = None, _UpperCAmelCase : Optional[int] = 1, _UpperCAmelCase : float = 0.0, _UpperCAmelCase : Optional[torch.Generator] = None, _UpperCAmelCase : Optional[torch.FloatTensor] = None, _UpperCAmelCase : Optional[str] = "pil", _UpperCAmelCase : bool = True, _UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None, _UpperCAmelCase : int = 1, **_UpperCAmelCase : Dict, ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.segmentation_processor( text=[text], images=[image], padding="max_length", return_tensors="pt" ).to(self.device ) SCREAMING_SNAKE_CASE__ : Tuple = self.segmentation_model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() SCREAMING_SNAKE_CASE__ : List[Any] = self.numpy_to_pil(_UpperCAmelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInpaintPipeline( vae=self.vae, text_encoder=self.text_encoder, tokenizer=self.tokenizer, unet=self.unet, scheduler=self.scheduler, safety_checker=self.safety_checker, feature_extractor=self.feature_extractor, ) return inpainting_pipeline( prompt=_UpperCAmelCase, image=_UpperCAmelCase, mask_image=_UpperCAmelCase, height=_UpperCAmelCase, width=_UpperCAmelCase, num_inference_steps=_UpperCAmelCase, guidance_scale=_UpperCAmelCase, negative_prompt=_UpperCAmelCase, num_images_per_prompt=_UpperCAmelCase, eta=_UpperCAmelCase, generator=_UpperCAmelCase, latents=_UpperCAmelCase, output_type=_UpperCAmelCase, return_dict=_UpperCAmelCase, callback=_UpperCAmelCase, callback_steps=_UpperCAmelCase, )
663
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase : Optional[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = ['''MobileViTFeatureExtractor'''] _lowerCamelCase : List[str] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[Any] = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = 42 UpperCAmelCase_ = jnp.floataa UpperCAmelCase_ = True def A_ ( self : Optional[int] ) -> Any: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ : int = nn.Dense(5, dtype=self.dtype ) def __call__( self : Dict, *_UpperCAmelCase : int, **_UpperCAmelCase : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = super().__call__(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = FlaxBigBirdForNaturalQuestionsModule def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: '''simple docstring''' def cross_entropy(SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int]=None ): SCREAMING_SNAKE_CASE__ : Optional[int] = logits.shape[-1] SCREAMING_SNAKE_CASE__ : str = (labels[..., None] == jnp.arange(SCREAMING_SNAKE_CASE__ )[None]).astype("f4" ) SCREAMING_SNAKE_CASE__ : Dict = jax.nn.log_softmax(SCREAMING_SNAKE_CASE__ , axis=-1 ) SCREAMING_SNAKE_CASE__ : str = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: SCREAMING_SNAKE_CASE__ : Tuple = reduction(SCREAMING_SNAKE_CASE__ ) return loss SCREAMING_SNAKE_CASE__ : Any = partial(SCREAMING_SNAKE_CASE__ , reduction=jnp.mean ) SCREAMING_SNAKE_CASE__ : Optional[int] = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = "google/bigbird-roberta-base" UpperCAmelCase_ = 3000 UpperCAmelCase_ = 10500 UpperCAmelCase_ = 128 UpperCAmelCase_ = 3 UpperCAmelCase_ = 1 UpperCAmelCase_ = 5 # tx_args UpperCAmelCase_ = 3E-5 UpperCAmelCase_ = 0.0 UpperCAmelCase_ = 20000 UpperCAmelCase_ = 0.0_095 UpperCAmelCase_ = "bigbird-roberta-natural-questions" UpperCAmelCase_ = "training-expt" UpperCAmelCase_ = "data/nq-training.jsonl" UpperCAmelCase_ = "data/nq-validation.jsonl" def A_ ( self : Tuple ) -> str: """simple docstring""" os.makedirs(self.base_dir, exist_ok=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(self.base_dir, self.save_dir ) SCREAMING_SNAKE_CASE__ : List[Any] = self.batch_size_per_device * jax.device_count() @dataclass class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = 42 UpperCAmelCase_ = 4096 # no dynamic padding on TPUs def __call__( self : List[str], _UpperCAmelCase : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.collate_fn(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = jax.tree_util.tree_map(_UpperCAmelCase, _UpperCAmelCase ) return batch def A_ ( self : Tuple, _UpperCAmelCase : int ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = self.fetch_inputs(features["input_ids"] ) SCREAMING_SNAKE_CASE__ : List[Any] = { "input_ids": jnp.array(_UpperCAmelCase, dtype=jnp.intaa ), "attention_mask": jnp.array(_UpperCAmelCase, dtype=jnp.intaa ), "start_labels": jnp.array(features["start_token"], dtype=jnp.intaa ), "end_labels": jnp.array(features["end_token"], dtype=jnp.intaa ), "pooled_labels": jnp.array(features["category"], dtype=jnp.intaa ), } return batch def A_ ( self : List[Any], _UpperCAmelCase : list ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [self._fetch_inputs(_UpperCAmelCase ) for ids in input_ids] return zip(*_UpperCAmelCase ) def A_ ( self : int, _UpperCAmelCase : list ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [1 for _ in range(len(_UpperCAmelCase ) )] while len(_UpperCAmelCase ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def _a ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int]=None ) -> Dict: '''simple docstring''' if seed is not None: SCREAMING_SNAKE_CASE__ : List[Any] = dataset.shuffle(seed=SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) // batch_size ): SCREAMING_SNAKE_CASE__ : List[str] = dataset[i * batch_size : (i + 1) * batch_size] yield dict(SCREAMING_SNAKE_CASE__ ) @partial(jax.pmap , axis_name="batch" ) def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: '''simple docstring''' def loss_fn(SCREAMING_SNAKE_CASE__ : int ): SCREAMING_SNAKE_CASE__ : str = model_inputs.pop("start_labels" ) SCREAMING_SNAKE_CASE__ : int = model_inputs.pop("end_labels" ) SCREAMING_SNAKE_CASE__ : int = model_inputs.pop("pooled_labels" ) SCREAMING_SNAKE_CASE__ : Dict = state.apply_fn(**SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ , dropout_rng=SCREAMING_SNAKE_CASE__ , train=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = outputs return state.loss_fn( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = jax.random.split(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[str] = jax.value_and_grad(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = grad_fn(state.params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.lax.pmean({"loss": loss} , axis_name="batch" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.lax.pmean(SCREAMING_SNAKE_CASE__ , "batch" ) SCREAMING_SNAKE_CASE__ : Dict = state.apply_gradients(grads=SCREAMING_SNAKE_CASE__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def _a ( SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = model_inputs.pop("start_labels" ) SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("end_labels" ) SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.pop("pooled_labels" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = state.apply_fn(**SCREAMING_SNAKE_CASE__ , params=state.params , train=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Any = outputs SCREAMING_SNAKE_CASE__ : int = state.loss_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class lowerCamelCase (train_state.TrainState ): """simple docstring""" UpperCAmelCase_ = struct.field(pytree_node=__lowerCamelCase ) @dataclass class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = None def A_ ( self : Tuple, _UpperCAmelCase : Tuple, _UpperCAmelCase : Optional[int], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int=None ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = model.params SCREAMING_SNAKE_CASE__ : int = TrainState.create( apply_fn=model.__call__, params=_UpperCAmelCase, tx=_UpperCAmelCase, loss_fn=_UpperCAmelCase, ) if ckpt_dir is not None: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = restore_checkpoint(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = { "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = build_tx(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = train_state.TrainState( step=_UpperCAmelCase, apply_fn=model.__call__, params=_UpperCAmelCase, tx=_UpperCAmelCase, opt_state=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : int = args SCREAMING_SNAKE_CASE__ : str = data_collator SCREAMING_SNAKE_CASE__ : List[Any] = lr SCREAMING_SNAKE_CASE__ : List[Any] = params SCREAMING_SNAKE_CASE__ : Any = jax_utils.replicate(_UpperCAmelCase ) return state def A_ ( self : Dict, _UpperCAmelCase : List[Any], _UpperCAmelCase : int, _UpperCAmelCase : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.args SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(_UpperCAmelCase ) // args.batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ : str = jax.random.split(_UpperCAmelCase, jax.device_count() ) for epoch in range(args.max_epochs ): SCREAMING_SNAKE_CASE__ : List[Any] = jnp.array(0, dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = get_batched_dataset(_UpperCAmelCase, args.batch_size, seed=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 0 for batch in tqdm(_UpperCAmelCase, total=_UpperCAmelCase, desc=F'''Running EPOCH-{epoch}''' ): SCREAMING_SNAKE_CASE__ : List[str] = self.data_collator(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = self.train_step_fn(_UpperCAmelCase, _UpperCAmelCase, **_UpperCAmelCase ) running_loss += jax_utils.unreplicate(metrics["loss"] ) i += 1 if i % args.logging_steps == 0: SCREAMING_SNAKE_CASE__ : Optional[int] = jax_utils.unreplicate(state.step ) SCREAMING_SNAKE_CASE__ : str = running_loss.item() / i SCREAMING_SNAKE_CASE__ : Dict = self.scheduler_fn(state_step - 1 ) SCREAMING_SNAKE_CASE__ : str = self.evaluate(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = { "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(_UpperCAmelCase ) ) self.logger.log(_UpperCAmelCase, commit=_UpperCAmelCase ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F'''-e{epoch}-s{i}''', state=_UpperCAmelCase ) def A_ ( self : Any, _UpperCAmelCase : Tuple, _UpperCAmelCase : Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = get_batched_dataset(_UpperCAmelCase, self.args.batch_size ) SCREAMING_SNAKE_CASE__ : List[str] = len(_UpperCAmelCase ) // self.args.batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.array(0, dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ : Dict = 0 for batch in tqdm(_UpperCAmelCase, total=_UpperCAmelCase, desc="Evaluating ... " ): SCREAMING_SNAKE_CASE__ : Optional[int] = self.data_collator(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.val_step_fn(_UpperCAmelCase, **_UpperCAmelCase ) running_loss += jax_utils.unreplicate(metrics["loss"] ) i += 1 return running_loss / i def A_ ( self : str, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = jax_utils.unreplicate(_UpperCAmelCase ) print(F'''SAVING CHECKPOINT IN {save_dir}''', end=" ... " ) self.model_save_fn(_UpperCAmelCase, params=state.params ) with open(os.path.join(_UpperCAmelCase, "opt_state.msgpack" ), "wb" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args, os.path.join(_UpperCAmelCase, "args.joblib" ) ) joblib.dump(self.data_collator, os.path.join(_UpperCAmelCase, "data_collator.joblib" ) ) with open(os.path.join(_UpperCAmelCase, "training_state.json" ), "w" ) as f: json.dump({"step": state.step.item()}, _UpperCAmelCase ) print("DONE" ) def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: '''simple docstring''' print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=" ... " ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , "flax_model.msgpack" ) , "rb" ) as f: SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_bytes(state.params , f.read() ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , "opt_state.msgpack" ) , "rb" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = from_bytes(state.opt_state , f.read() ) SCREAMING_SNAKE_CASE__ : str = joblib.load(os.path.join(SCREAMING_SNAKE_CASE__ , "args.joblib" ) ) SCREAMING_SNAKE_CASE__ : List[str] = joblib.load(os.path.join(SCREAMING_SNAKE_CASE__ , "data_collator.joblib" ) ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , "training_state.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE__ : List[Any] = json.load(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = num_train_steps - warmup_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__ , end_value=SCREAMING_SNAKE_CASE__ , transition_steps=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__ , end_value=1E-7 , transition_steps=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def _a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: '''simple docstring''' def weight_decay_mask(SCREAMING_SNAKE_CASE__ : Tuple ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = traverse_util.flatten_dict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = optax.adamw(learning_rate=SCREAMING_SNAKE_CASE__ , weight_decay=SCREAMING_SNAKE_CASE__ , mask=SCREAMING_SNAKE_CASE__ ) return tx, lr
663
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = BlenderbotSmallConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Optional[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : Optional[int]=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : List[Any]=True, _UpperCAmelCase : Union[str, Any]=False, _UpperCAmelCase : str=9_9, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Any=2, _UpperCAmelCase : Any=4, _UpperCAmelCase : List[Any]=3_7, _UpperCAmelCase : Dict=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=2_0, _UpperCAmelCase : int=2, _UpperCAmelCase : Union[str, Any]=1, _UpperCAmelCase : List[str]=0, ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = eos_token_id SCREAMING_SNAKE_CASE__ : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE__ : List[Any] = bos_token_id def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Dict = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Any = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : str = prepare_blenderbot_small_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFBlenderbotSmallModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Optional[Any] = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : List[str] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : Tuple = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Dict = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : int = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Any = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Tuple = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : Tuple = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) UpperCAmelCase_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFBlenderbotSmallForConditionalGeneration, "feature-extraction": TFBlenderbotSmallModel, "summarization": TFBlenderbotSmallForConditionalGeneration, "text2text-generation": TFBlenderbotSmallForConditionalGeneration, "translation": TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFBlenderbotSmallModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[int] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Any ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like " " i'm going to throw up.\nand why is that?" ] UpperCAmelCase_ = "facebook/blenderbot_small-90M" @cached_property def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def A_ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
663
1
import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = IFInpaintingPipeline UpperCAmelCase_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} UpperCAmelCase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCAmelCase_ = PipelineTesterMixin.required_optional_params - {"latents"} def A_ ( self : List[Any] ) -> Dict: """simple docstring""" return self._get_dummy_components() def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : str=0 ) -> Union[str, Any]: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, 3, 3_2, 3_2), rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 3_2, 3_2), rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "image": image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available(), reason="XFormers attention is only available with CUDA and `xformers` installed", ) def A_ ( self : Optional[Any] ) -> Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def A_ ( self : int ) -> List[str]: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda", reason="float16 requires CUDA" ) def A_ ( self : Dict ) -> str: """simple docstring""" # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def A_ ( self : Tuple ) -> Union[str, Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def A_ ( self : Dict ) -> Tuple: """simple docstring""" self._test_save_load_local() def A_ ( self : Union[str, Any] ) -> str: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2, )
663
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (DPMSolverSDEScheduler,) UpperCAmelCase_ = 10 def A_ ( self : List[str], **_UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "noise_sampler_seed": 0, } config.update(**_UpperCAmelCase ) return config def A_ ( self : Tuple ) -> int: """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_UpperCAmelCase ) def A_ ( self : int ) -> int: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001], [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_UpperCAmelCase, beta_end=_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : int = self.dummy_model() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Union[str, Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Dict = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config(prediction_type="v_prediction" ) SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Tuple = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def A_ ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : int = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Tuple = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Any = scheduler_class(**_UpperCAmelCase, use_karras_sigmas=_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : str = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
663
1
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCamelCase : Optional[int] = logging.get_logger(__name__) _lowerCamelCase : Dict = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', } _lowerCamelCase : int = { '''vocab_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'''}, '''merges_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'''}, } _lowerCamelCase : str = { '''ctrl''': 2_5_6, } _lowerCamelCase : Union[str, Any] = { '''Pregnancy''': 1_6_8_6_2_9, '''Christianity''': 7_6_7_5, '''Explain''': 1_0_6_4_2_3, '''Fitness''': 6_3_4_4_0, '''Saving''': 6_3_1_6_3, '''Ask''': 2_7_1_7_1, '''Ass''': 9_5_9_8_5, '''Joke''': 1_6_3_5_0_9, '''Questions''': 4_5_6_2_2, '''Thoughts''': 4_9_6_0_5, '''Retail''': 5_2_3_4_2, '''Feminism''': 1_6_4_3_3_8, '''Writing''': 1_1_9_9_2, '''Atheism''': 1_9_2_2_6_3, '''Netflix''': 4_8_6_1_6, '''Computing''': 3_9_6_3_9, '''Opinion''': 4_3_2_1_3, '''Alone''': 4_4_9_6_7, '''Funny''': 5_8_9_1_7, '''Gaming''': 4_0_3_5_8, '''Human''': 4_0_8_8, '''India''': 1_3_3_1, '''Joker''': 7_7_1_3_8, '''Diet''': 3_6_2_0_6, '''Legal''': 1_1_8_5_9, '''Norman''': 4_9_3_9, '''Tip''': 7_2_6_8_9, '''Weight''': 5_2_3_4_3, '''Movies''': 4_6_2_7_3, '''Running''': 2_3_4_2_5, '''Science''': 2_0_9_0, '''Horror''': 3_7_7_9_3, '''Confession''': 6_0_5_7_2, '''Finance''': 1_2_2_5_0, '''Politics''': 1_6_3_6_0, '''Scary''': 1_9_1_9_8_5, '''Support''': 1_2_6_5_4, '''Technologies''': 3_2_5_1_6, '''Teenage''': 6_6_1_6_0, '''Event''': 3_2_7_6_9, '''Learned''': 6_7_4_6_0, '''Notion''': 1_8_2_7_7_0, '''Wikipedia''': 3_7_5_8_3, '''Books''': 6_6_6_5, '''Extract''': 7_6_0_5_0, '''Confessions''': 1_0_2_7_0_1, '''Conspiracy''': 7_5_9_3_2, '''Links''': 6_3_6_7_4, '''Narcissus''': 1_5_0_4_2_5, '''Relationship''': 5_4_7_6_6, '''Relationships''': 1_3_4_7_9_6, '''Reviews''': 4_1_6_7_1, '''News''': 4_2_5_6, '''Translation''': 2_6_8_2_0, '''multilingual''': 1_2_8_4_0_6, } def _a ( SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = set() SCREAMING_SNAKE_CASE__ : Optional[int] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE__ : Any = char SCREAMING_SNAKE_CASE__ : List[Any] = set(SCREAMING_SNAKE_CASE__ ) return pairs class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = CONTROL_CODES def __init__( self : Optional[int], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Union[str, Any]="<unk>", **_UpperCAmelCase : Dict ) -> Optional[Any]: """simple docstring""" super().__init__(unk_token=_UpperCAmelCase, **_UpperCAmelCase ) with open(_UpperCAmelCase, encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.load(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = {v: k for k, v in self.encoder.items()} with open(_UpperCAmelCase, encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE__ : Dict = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE__ : Any = [tuple(merge.split() ) for merge in merges] SCREAMING_SNAKE_CASE__ : List[Any] = dict(zip(_UpperCAmelCase, range(len(_UpperCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = {} @property def A_ ( self : List[Any] ) -> Tuple: """simple docstring""" return len(self.encoder ) def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" return dict(self.encoder, **self.added_tokens_encoder ) def A_ ( self : int, _UpperCAmelCase : Dict ) -> Any: """simple docstring""" if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE__ : List[str] = tuple(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) SCREAMING_SNAKE_CASE__ : Any = get_pairs(_UpperCAmelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE__ : Optional[int] = min(_UpperCAmelCase, key=lambda _UpperCAmelCase : self.bpe_ranks.get(_UpperCAmelCase, float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = bigram SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 while i < len(_UpperCAmelCase ): try: SCREAMING_SNAKE_CASE__ : int = word.index(_UpperCAmelCase, _UpperCAmelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE__ : List[Any] = j if word[i] == first and i < len(_UpperCAmelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE__ : str = tuple(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_word if len(_UpperCAmelCase ) == 1: break else: SCREAMING_SNAKE_CASE__ : Dict = get_pairs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = "@@ ".join(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = word[:-4] SCREAMING_SNAKE_CASE__ : List[str] = word return word def A_ ( self : Tuple, _UpperCAmelCase : Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : str = re.findall(r"\S+\n?", _UpperCAmelCase ) for token in words: split_tokens.extend(list(self.bpe(_UpperCAmelCase ).split(" " ) ) ) return split_tokens def A_ ( self : List[str], _UpperCAmelCase : Optional[int] ) -> str: """simple docstring""" return self.encoder.get(_UpperCAmelCase, self.encoder.get(self.unk_token ) ) def A_ ( self : Tuple, _UpperCAmelCase : str ) -> str: """simple docstring""" return self.decoder.get(_UpperCAmelCase, self.unk_token ) def A_ ( self : Union[str, Any], _UpperCAmelCase : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = " ".join(_UpperCAmelCase ).replace("@@ ", "" ).strip() return out_string def A_ ( self : List[str], _UpperCAmelCase : str, _UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_UpperCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : str = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_UpperCAmelCase, "w", encoding="utf-8" ) as f: f.write(json.dumps(self.encoder, indent=2, sort_keys=_UpperCAmelCase, ensure_ascii=_UpperCAmelCase ) + "\n" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 with open(_UpperCAmelCase, "w", encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda _UpperCAmelCase : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE__ : str = token_index writer.write(" ".join(_UpperCAmelCase ) + "\n" ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
663
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = ["image_processor", "tokenizer"] UpperCAmelCase_ = "AutoImageProcessor" UpperCAmelCase_ = "AutoTokenizer" def __init__( self : Tuple, _UpperCAmelCase : str=None, _UpperCAmelCase : str=None, **_UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead.", _UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop("feature_extractor" ) SCREAMING_SNAKE_CASE__ : Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.image_processor SCREAMING_SNAKE_CASE__ : Any = False def __call__( self : List[str], *_UpperCAmelCase : Any, **_UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("images", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = args[0] SCREAMING_SNAKE_CASE__ : str = args[1:] if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: SCREAMING_SNAKE_CASE__ : Dict = self.image_processor(_UpperCAmelCase, *_UpperCAmelCase, **_UpperCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if text is None: return inputs elif images is None: return encodings else: SCREAMING_SNAKE_CASE__ : Optional[int] = encodings["input_ids"] return inputs def A_ ( self : Dict, *_UpperCAmelCase : Tuple, **_UpperCAmelCase : Dict ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : List[str], *_UpperCAmelCase : int, **_UpperCAmelCase : Dict ) -> Any: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) @contextmanager def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your images inputs, or in a separate call." ) SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False def A_ ( self : Tuple, _UpperCAmelCase : List[Any], _UpperCAmelCase : int=False, _UpperCAmelCase : Optional[Any]=None ) -> Any: """simple docstring""" if added_vocab is None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer.get_added_vocab() SCREAMING_SNAKE_CASE__ : str = {} while tokens: SCREAMING_SNAKE_CASE__ : Dict = re.search(r"<s_(.*?)>", _UpperCAmelCase, re.IGNORECASE ) if start_token is None: break SCREAMING_SNAKE_CASE__ : Any = start_token.group(1 ) SCREAMING_SNAKE_CASE__ : Dict = re.search(rF'''</s_{key}>''', _UpperCAmelCase, re.IGNORECASE ) SCREAMING_SNAKE_CASE__ : Any = start_token.group() if end_token is None: SCREAMING_SNAKE_CASE__ : List[str] = tokens.replace(_UpperCAmelCase, "" ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = end_token.group() SCREAMING_SNAKE_CASE__ : List[str] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}''', _UpperCAmelCase, re.IGNORECASE ) if content is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node SCREAMING_SNAKE_CASE__ : str = self.tokenajson(_UpperCAmelCase, is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if value: if len(_UpperCAmelCase ) == 1: SCREAMING_SNAKE_CASE__ : str = value[0] SCREAMING_SNAKE_CASE__ : List[str] = value else: # leaf nodes SCREAMING_SNAKE_CASE__ : Optional[int] = [] for leaf in content.split(r"<sep/>" ): SCREAMING_SNAKE_CASE__ : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": SCREAMING_SNAKE_CASE__ : str = leaf[1:-2] # for categorical special tokens output[key].append(_UpperCAmelCase ) if len(output[key] ) == 1: SCREAMING_SNAKE_CASE__ : str = output[key][0] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokens[tokens.find(_UpperCAmelCase ) + len(_UpperCAmelCase ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if len(_UpperCAmelCase ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def A_ ( self : str ) -> Optional[Any]: """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.", _UpperCAmelCase, ) return self.image_processor_class @property def A_ ( self : int ) -> List[str]: """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.", _UpperCAmelCase, ) return self.image_processor
663
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase : Optional[int] = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Tuple = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = ['''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 : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _lowerCamelCase : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = ['''BartphoTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
from __future__ import annotations _lowerCamelCase : List[Any] = 8.9_8_8e9 # units = N * m^s * C^-2 def _a ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ) -> dict[str, float]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if distance < 0: raise ValueError("Distance cannot be negative" ) if force == 0: SCREAMING_SNAKE_CASE__ : List[str] = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: SCREAMING_SNAKE_CASE__ : List[str] = abs(SCREAMING_SNAKE_CASE__ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = abs(SCREAMING_SNAKE_CASE__ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (COULOMBS_CONSTANT * charge_product / abs(SCREAMING_SNAKE_CASE__ )) ** 0.5 return {"distance": distance} raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
663
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class lowerCamelCase : """simple docstring""" def __init__( self : Any, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Union[str, Any]=1_3, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : str=1_6, _UpperCAmelCase : Tuple=[1, 2, 1], _UpperCAmelCase : List[str]=[2, 2, 4], _UpperCAmelCase : Tuple=2, _UpperCAmelCase : str=2.0, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=0.0, _UpperCAmelCase : Any=0.0, _UpperCAmelCase : Optional[int]=0.1, _UpperCAmelCase : int="gelu", _UpperCAmelCase : Any=False, _UpperCAmelCase : Any=True, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Any=1E-5, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : List[Any]=None, _UpperCAmelCase : str=True, _UpperCAmelCase : Union[str, Any]=1_0, _UpperCAmelCase : List[str]=8, _UpperCAmelCase : Union[str, Any]=["stage1", "stage2", "stage3"], _UpperCAmelCase : Any=[1, 2, 3], ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = embed_dim SCREAMING_SNAKE_CASE__ : List[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = num_heads SCREAMING_SNAKE_CASE__ : str = window_size SCREAMING_SNAKE_CASE__ : Any = mlp_ratio SCREAMING_SNAKE_CASE__ : List[str] = qkv_bias SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = drop_path_rate SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Tuple = patch_norm SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : Optional[int] = use_labels SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_stride SCREAMING_SNAKE_CASE__ : List[Any] = out_features SCREAMING_SNAKE_CASE__ : Dict = out_indices def A_ ( self : List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[int] ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, out_features=self.out_features, out_indices=self.out_indices, ) def A_ ( self : Dict, _UpperCAmelCase : int, _UpperCAmelCase : str, _UpperCAmelCase : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def A_ ( self : Optional[int], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any, _UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = MaskFormerSwinBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ), len(config.out_features ) ) self.parent.assertListEqual(model.channels, [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = ["stem"] SCREAMING_SNAKE_CASE__ : str = MaskFormerSwinBackbone(config=_UpperCAmelCase ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) UpperCAmelCase_ = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = MaskFormerSwinModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = ConfigTester(self, config_class=_UpperCAmelCase, embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def A_ ( self : Any ) -> List[Any]: """simple docstring""" pass def A_ ( self : Tuple ) -> Any: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A_ ( self : int ) -> Optional[Any]: """simple docstring""" return def A_ ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_UpperCAmelCase ) @unittest.skip("Swin does not use inputs_embeds" ) def A_ ( self : Any ) -> Optional[int]: """simple docstring""" pass @unittest.skip("Swin does not support feedforward chunking" ) def A_ ( self : List[str] ) -> Optional[int]: """simple docstring""" pass def A_ ( self : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, nn.Linear ) ) def A_ ( self : Union[str, Any] ) -> List[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__ : Dict = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def A_ ( self : Dict ) -> List[str]: """simple docstring""" pass def A_ ( self : List[str], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr( self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_UpperCAmelCase ), _UpperCAmelCase ) # Swin has a different seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Dict = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Any = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def A_ ( self : List[Any] ) -> Dict: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Dict ) -> str: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" pass def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_UpperCAmelCase : Optional[Any] ): SCREAMING_SNAKE_CASE__ : Dict = 0 return t def check_equivalence(_UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : Optional[Any]={} ): with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ).to_tuple() def recursive_check(_UpperCAmelCase : int, _UpperCAmelCase : Dict ): if isinstance(_UpperCAmelCase, (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_UpperCAmelCase, _UpperCAmelCase ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif isinstance(_UpperCAmelCase, _UpperCAmelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values(), dict_object.values() ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_UpperCAmelCase ), set_nan_tensor_to_zero(_UpperCAmelCase ), atol=1E-5 ), msg=( "Tuple and dict output are not equal. Difference:" F''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' F''' {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}. Dict has''' F''' `nan`: {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}.''' ), ) recursive_check(_UpperCAmelCase, _UpperCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) @require_torch class lowerCamelCase (unittest.TestCase , __lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (MaskFormerSwinBackbone,) if is_torch_available() else () UpperCAmelCase_ = MaskFormerSwinConfig def A_ ( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModelTester(self ) def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = backbone_class(_UpperCAmelCase ) backbone.to(_UpperCAmelCase ) backbone.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps, _UpperCAmelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels ): self.assertTrue(feature_map.shape[:2], (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase, output_hidden_states=_UpperCAmelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ), len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:], backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels), (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: SCREAMING_SNAKE_CASE__ : int = backbone(**_UpperCAmelCase, output_attentions=_UpperCAmelCase ) self.assertIsNotNone(outputs.attentions )
663
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss _lowerCamelCase : str = pytest.mark.integration @require_faiss class lowerCamelCase (__lowerCamelCase ): """simple docstring""" def A_ ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(_UpperCAmelCase ) for x in np.arange(3_0 ).tolist()]} ) return dset def A_ ( self : int ) -> Optional[Any]: """simple docstring""" import faiss SCREAMING_SNAKE_CASE__ : Dataset = self._create_dummy_dataset() SCREAMING_SNAKE_CASE__ : Optional[Any] = dset.map( lambda _UpperCAmelCase, _UpperCAmelCase : {"vecs": i * np.ones(5, dtype=np.floataa )}, with_indices=_UpperCAmelCase, keep_in_memory=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = dset.add_faiss_index("vecs", batch_size=1_0_0, metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = dset.get_nearest_examples("vecs", np.ones(5, dtype=np.floataa ) ) self.assertEqual(examples["filename"][0], "my_name-train_29" ) dset.drop_index("vecs" ) def A_ ( self : int ) -> str: """simple docstring""" import faiss SCREAMING_SNAKE_CASE__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1, 1 ), index_name="vecs", batch_size=1_0_0, metric_type=faiss.METRIC_INNER_PRODUCT, ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = dset.get_nearest_examples("vecs", np.ones(5, dtype=np.floataa ) ) self.assertEqual(examples["filename"][0], "my_name-train_29" ) def A_ ( self : Any ) -> List[Any]: """simple docstring""" import faiss SCREAMING_SNAKE_CASE__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1, 1 ), index_name="vecs", metric_type=faiss.METRIC_INNER_PRODUCT, ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_UpperCAmelCase ) as tmp_file: dset.save_faiss_index("vecs", tmp_file.name ) dset.load_faiss_index("vecs2", tmp_file.name ) os.unlink(tmp_file.name ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = dset.get_nearest_examples("vecs2", np.ones(5, dtype=np.floataa ) ) self.assertEqual(examples["filename"][0], "my_name-train_29" ) def A_ ( self : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1, 1 ), index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(_UpperCAmelCase, partial(dset.get_nearest_examples, "vecs2", np.ones(5, dtype=np.floataa ) ) ) def A_ ( self : Dict ) -> Tuple: """simple docstring""" from elasticsearch import Elasticsearch SCREAMING_SNAKE_CASE__ : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: SCREAMING_SNAKE_CASE__ : Optional[Any] = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 3_0 ) SCREAMING_SNAKE_CASE__ : Dict = {"hits": {"hits": [{"_score": 1, "_id": 2_9}]}} SCREAMING_SNAKE_CASE__ : str = Elasticsearch() dset.add_elasticsearch_index("filename", es_client=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = dset.get_nearest_examples("filename", "my_name-train_29" ) self.assertEqual(examples["filename"][0], "my_name-train_29" ) @require_faiss class lowerCamelCase (__lowerCamelCase ): """simple docstring""" def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" import faiss SCREAMING_SNAKE_CASE__ : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5, dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal, 5 ) index.add_vectors(np.zeros((5, 5), dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal, 1_0 ) # single query SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros(5, dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = 1 SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = index.search(_UpperCAmelCase ) self.assertRaises(_UpperCAmelCase, index.search, query.reshape(-1, 1 ) ) self.assertGreater(scores[0], 0 ) self.assertEqual(indices[0], 1 ) # batched queries SCREAMING_SNAKE_CASE__ : str = np.eye(5, dtype=np.floataa )[::-1] SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = index.search_batch(_UpperCAmelCase ) self.assertRaises(_UpperCAmelCase, index.search_batch, queries[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = [scores[0] for scores in total_scores] SCREAMING_SNAKE_CASE__ : str = [indices[0] for indices in total_indices] self.assertGreater(np.min(_UpperCAmelCase ), 0 ) self.assertListEqual([4, 3, 2, 1, 0], _UpperCAmelCase ) def A_ ( self : Optional[int] ) -> str: """simple docstring""" import faiss SCREAMING_SNAKE_CASE__ : Optional[int] = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index, faiss.IndexFlat ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index, faiss.IndexLSH ) with self.assertRaises(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = FaissIndex(string_factory="Flat", custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : Any ) -> Optional[int]: """simple docstring""" import faiss SCREAMING_SNAKE_CASE__ : Optional[int] = faiss.IndexFlat(5 ) SCREAMING_SNAKE_CASE__ : Dict = FaissIndex(custom_index=_UpperCAmelCase ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index, faiss.IndexFlat ) def A_ ( self : Dict ) -> str: """simple docstring""" import faiss SCREAMING_SNAKE_CASE__ : List[str] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) SCREAMING_SNAKE_CASE__ : Dict = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.zeros(5, dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = index.search(_UpperCAmelCase ) self.assertGreater(scores[0], 0 ) self.assertEqual(indices[0], 1 ) @require_faiss def _a ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: '''simple docstring''' import faiss SCREAMING_SNAKE_CASE__ : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) SCREAMING_SNAKE_CASE__ : int = "index.faiss" SCREAMING_SNAKE_CASE__ : Optional[int] = f'''mock://{index_name}''' index.save(SCREAMING_SNAKE_CASE__ , storage_options=mockfs.storage_options ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FaissIndex.load(SCREAMING_SNAKE_CASE__ , storage_options=mockfs.storage_options ) SCREAMING_SNAKE_CASE__ : str = np.zeros(5 , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = 1 SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = index.search(SCREAMING_SNAKE_CASE__ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowerCamelCase (__lowerCamelCase ): """simple docstring""" def A_ ( self : int ) -> int: """simple docstring""" from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: SCREAMING_SNAKE_CASE__ : Dict = Elasticsearch() SCREAMING_SNAKE_CASE__ : Tuple = {"acknowledged": True} SCREAMING_SNAKE_CASE__ : Optional[int] = ElasticSearchIndex(es_client=_UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query SCREAMING_SNAKE_CASE__ : List[str] = "foo" SCREAMING_SNAKE_CASE__ : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = index.search(_UpperCAmelCase ) self.assertEqual(scores[0], 1 ) self.assertEqual(indices[0], 0 ) # single query with timeout SCREAMING_SNAKE_CASE__ : Optional[Any] = "foo" SCREAMING_SNAKE_CASE__ : Optional[int] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = index.search(_UpperCAmelCase, request_timeout=3_0 ) self.assertEqual(scores[0], 1 ) self.assertEqual(indices[0], 0 ) # batched queries SCREAMING_SNAKE_CASE__ : Any = ["foo", "bar", "foobar"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Tuple = index.search_batch(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [scores[0] for scores in total_scores] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_UpperCAmelCase ), 0 ) self.assertListEqual([1, 1, 1], _UpperCAmelCase ) # batched queries with timeout SCREAMING_SNAKE_CASE__ : Optional[Any] = ["foo", "bar", "foobar"] SCREAMING_SNAKE_CASE__ : Tuple = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = index.search_batch(_UpperCAmelCase, request_timeout=3_0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [scores[0] for scores in total_scores] SCREAMING_SNAKE_CASE__ : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(_UpperCAmelCase ), 0 ) self.assertListEqual([1, 1, 1], _UpperCAmelCase )
663
from ....configuration_utils import PretrainedConfig from ....utils import logging _lowerCamelCase : Any = logging.get_logger(__name__) # TODO: upload to AWS _lowerCamelCase : str = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json''' ), } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "retribert" def __init__( self : Optional[Any], _UpperCAmelCase : Dict=3_0_5_2_2, _UpperCAmelCase : List[str]=7_6_8, _UpperCAmelCase : Tuple=8, _UpperCAmelCase : Optional[Any]=1_2, _UpperCAmelCase : Union[str, Any]=3_0_7_2, _UpperCAmelCase : Dict="gelu", _UpperCAmelCase : Tuple=0.1, _UpperCAmelCase : str=0.1, _UpperCAmelCase : List[str]=5_1_2, _UpperCAmelCase : Optional[int]=2, _UpperCAmelCase : Dict=0.02, _UpperCAmelCase : Any=1E-12, _UpperCAmelCase : Dict=True, _UpperCAmelCase : Any=1_2_8, _UpperCAmelCase : int=0, **_UpperCAmelCase : List[str], ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = share_encoders SCREAMING_SNAKE_CASE__ : int = projection_dim
663
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : int = {'''configuration_wavlm''': ['''WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WavLMConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Tuple = [ '''WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''WavLMForAudioFrameClassification''', '''WavLMForCTC''', '''WavLMForSequenceClassification''', '''WavLMForXVector''', '''WavLMModel''', '''WavLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin _lowerCamelCase : int = False @skip_mps class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = StableDiffusionAttendAndExcitePipeline UpperCAmelCase_ = False UpperCAmelCase_ = TEXT_TO_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"} ) UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def A_ ( cls : str ) -> Union[str, Any]: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : Tuple ) -> str: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : Any ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4), layers_per_block=1, sample_size=3_2, in_channels=4, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=3_2, attention_head_dim=(2, 4), use_linear_projection=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=_UpperCAmelCase, set_alpha_to_one=_UpperCAmelCase, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = AutoencoderKL( block_out_channels=[3_2, 6_4], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, sample_size=1_2_8, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=3_2, intermediate_size=3_7, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, hidden_act="gelu", projection_dim=5_1_2, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTextModel(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def A_ ( self : Optional[Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Any=0 ) -> Optional[Any]: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : Tuple = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = { "prompt": "a cat and a frog", "token_indices": [2, 5], "generator": generator, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", "max_iter_to_alter": 2, "thresholds": {0: 0.7}, } return inputs def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = "cpu" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.pipeline_class(**_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_dummy_inputs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = pipe(**_UpperCAmelCase ).images SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 6_4, 6_4, 3) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) SCREAMING_SNAKE_CASE__ : Dict = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_UpperCAmelCase, 1E-3 ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def A_ ( self : Any ) -> str: """simple docstring""" # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : Optional[Any] ) -> str: """simple docstring""" self._test_inference_batch_single_identical(batch_size=2, expected_max_diff=7E-4 ) def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def A_ ( self : Any ) -> List[str]: """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" super().test_save_load_local(expected_max_difference=5E-4 ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class lowerCamelCase (unittest.TestCase ): """simple docstring""" @classmethod def A_ ( cls : Union[str, Any] ) -> Tuple: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : List[str] ) -> List[str]: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(5_1 ) SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionAttendAndExcitePipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=_UpperCAmelCase, torch_dtype=torch.floataa ) pipe.to("cuda" ) SCREAMING_SNAKE_CASE__ : List[str] = "a painting of an elephant with glasses" SCREAMING_SNAKE_CASE__ : Optional[int] = [5, 7] SCREAMING_SNAKE_CASE__ : str = pipe( prompt=_UpperCAmelCase, token_indices=_UpperCAmelCase, guidance_scale=7.5, generator=_UpperCAmelCase, num_inference_steps=5, max_iter_to_alter=5, output_type="numpy", ).images[0] SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy" ) assert np.abs((expected_image - image).max() ) < 5E-1
663
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : List[str] = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''', # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "pegasus" UpperCAmelCase_ = ["past_key_values"] UpperCAmelCase_ = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Any, _UpperCAmelCase : List[str]=5_0_2_6_5, _UpperCAmelCase : int=1_0_2_4, _UpperCAmelCase : Any=1_2, _UpperCAmelCase : List[str]=4_0_9_6, _UpperCAmelCase : Any=1_6, _UpperCAmelCase : Any=1_2, _UpperCAmelCase : Tuple=4_0_9_6, _UpperCAmelCase : int=1_6, _UpperCAmelCase : Any=0.0, _UpperCAmelCase : str=0.0, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Any=True, _UpperCAmelCase : str="gelu", _UpperCAmelCase : Any=1_0_2_4, _UpperCAmelCase : Optional[Any]=0.1, _UpperCAmelCase : Union[str, Any]=0.0, _UpperCAmelCase : Union[str, Any]=0.0, _UpperCAmelCase : Optional[int]=0.02, _UpperCAmelCase : Union[str, Any]=0, _UpperCAmelCase : str=False, _UpperCAmelCase : List[str]=0, _UpperCAmelCase : int=1, _UpperCAmelCase : Any=1, **_UpperCAmelCase : Any, ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = vocab_size SCREAMING_SNAKE_CASE__ : str = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_model SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : List[str] = encoder_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_layers SCREAMING_SNAKE_CASE__ : Dict = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = dropout SCREAMING_SNAKE_CASE__ : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE__ : str = activation_dropout SCREAMING_SNAKE_CASE__ : str = activation_function SCREAMING_SNAKE_CASE__ : Dict = init_std SCREAMING_SNAKE_CASE__ : Any = encoder_layerdrop SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_layerdrop SCREAMING_SNAKE_CASE__ : Dict = use_cache SCREAMING_SNAKE_CASE__ : Tuple = encoder_layers SCREAMING_SNAKE_CASE__ : int = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=_UpperCAmelCase, eos_token_id=_UpperCAmelCase, is_encoder_decoder=_UpperCAmelCase, decoder_start_token_id=_UpperCAmelCase, forced_eos_token_id=_UpperCAmelCase, **_UpperCAmelCase, ) @property def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A_ ( self : List[str] ) -> int: """simple docstring""" return self.d_model
663
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = PegasusConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=False, _UpperCAmelCase : Union[str, Any]=9_9, _UpperCAmelCase : Optional[Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=4, _UpperCAmelCase : str=3_7, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=4_0, _UpperCAmelCase : Any=2, _UpperCAmelCase : int=1, _UpperCAmelCase : str=0, ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : str = eos_token_id SCREAMING_SNAKE_CASE__ : Dict = pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = bos_token_id def A_ ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_pegasus_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Union[str, Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFPegasusModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : str = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : int = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : int = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : str = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Optional[Any] = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : List[str]=None , ) -> Any: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase_ = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFPegasusModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_sentencepiece @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] UpperCAmelCase_ = [ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to" " reduce the risk of wildfires.", "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.", ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase_ = "google/pegasus-xsum" @cached_property def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def A_ ( self : str, **_UpperCAmelCase : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.translate_src_text(**_UpperCAmelCase ) assert self.expected_text == generated_words def A_ ( self : Any, **_UpperCAmelCase : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, **_UpperCAmelCase, padding=_UpperCAmelCase, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : List[str] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase ) return generated_words @slow def A_ ( self : List[Any] ) -> Any: """simple docstring""" self._assert_generated_batch_equal_expected()
663
1
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _a ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = s.rsplit(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return new.join(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : str ) -> Tuple: '''simple docstring''' return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def _a ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = {} SCREAMING_SNAKE_CASE__ : Any = ["group_1", "group_2", "group_3", "group_4"] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: SCREAMING_SNAKE_CASE__ : Optional[int] = key.replace(f'''{group_key}.''' , f'''{group_key}.group.''' ) if "res_path" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] = key.replace("res_path." , "res_path.path." ) if key.endswith(".w" ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = rreplace(SCREAMING_SNAKE_CASE__ , ".w" , ".weight" , 1 ) if key.endswith(".b" ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = rreplace(SCREAMING_SNAKE_CASE__ , ".b" , ".bias" , 1 ) SCREAMING_SNAKE_CASE__ : int = value.float() return upgrade @torch.no_grad() def _a ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Any=True ) -> int: '''simple docstring''' from dall_e import Encoder SCREAMING_SNAKE_CASE__ : List[Any] = Encoder() if os.path.exists(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Tuple = torch.load(SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ckpt.state_dict() encoder.load_state_dict(SCREAMING_SNAKE_CASE__ ) if config_path is not None: SCREAMING_SNAKE_CASE__ : List[Any] = FlavaImageCodebookConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : str = FlavaImageCodebookConfig() SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlavaImageCodebook(SCREAMING_SNAKE_CASE__ ).eval() SCREAMING_SNAKE_CASE__ : Tuple = encoder.state_dict() SCREAMING_SNAKE_CASE__ : int = upgrade_state_dict(SCREAMING_SNAKE_CASE__ ) hf_model.load_state_dict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = hf_model.state_dict() SCREAMING_SNAKE_CASE__ : Optional[Any] = count_parameters(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = count_parameters(SCREAMING_SNAKE_CASE__ ) assert torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) if save_checkpoint: hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) else: return hf_state_dict if __name__ == "__main__": _lowerCamelCase : Any = 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 flava checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') _lowerCamelCase : int = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase : List[str] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def _a ( ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = ArgumentParser("Accelerate CLI tool" , usage="accelerate <command> [<args>]" , allow_abbrev=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = parser.add_subparsers(help="accelerate command helpers" ) # Register commands get_config_parser(subparsers=SCREAMING_SNAKE_CASE__ ) env_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) launch_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) tpu_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) test_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) # Let's go SCREAMING_SNAKE_CASE__ : int = parser.parse_args() if not hasattr(SCREAMING_SNAKE_CASE__ , "func" ): parser.print_help() exit(1 ) # Run args.func(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
663
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = '''Hello world! cécé herlolip''' def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = FairseqRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) roberta.eval() # disable dropout SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.sentence_encoder SCREAMING_SNAKE_CASE__ : List[str] = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaXLForSequenceClassification(SCREAMING_SNAKE_CASE__ ) if classification_head else XLMRobertaXLForMaskedLM(SCREAMING_SNAKE_CASE__ ) model.eval() # Now let's copy all the weights. # Embeddings SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.embed_tokens.weight SCREAMING_SNAKE_CASE__ : str = roberta_sent_encoder.embed_positions.weight SCREAMING_SNAKE_CASE__ : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. SCREAMING_SNAKE_CASE__ : Any = roberta_sent_encoder.layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer SCREAMING_SNAKE_CASE__ : BertLayer = model.roberta.encoder.layer[i] SCREAMING_SNAKE_CASE__ : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] SCREAMING_SNAKE_CASE__ : RobertaAttention = layer.attention SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn_layer_norm.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn_layer_norm.bias # self attention SCREAMING_SNAKE_CASE__ : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = roberta_layer.self_attn.q_proj.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.self_attn.q_proj.bias SCREAMING_SNAKE_CASE__ : Any = roberta_layer.self_attn.k_proj.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn.k_proj.bias SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.self_attn.v_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.self_attn.v_proj.bias # self-attention output SCREAMING_SNAKE_CASE__ : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.weight SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.bias # this one is final layer norm SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.bias # intermediate SCREAMING_SNAKE_CASE__ : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.bias # output SCREAMING_SNAKE_CASE__ : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.fca.bias # end of layer if classification_head: SCREAMING_SNAKE_CASE__ : str = roberta.model.classification_heads["mnli"].dense.weight SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"].dense.bias SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head SCREAMING_SNAKE_CASE__ : Tuple = roberta.model.encoder.lm_head.dense.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.dense.bias SCREAMING_SNAKE_CASE__ : List[str] = roberta.model.encoder.lm_head.layer_norm.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta.model.encoder.lm_head.layer_norm.bias SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.encoder.lm_head.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. SCREAMING_SNAKE_CASE__ : torch.Tensor = roberta.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) # batch of size 1 SCREAMING_SNAKE_CASE__ : int = model(SCREAMING_SNAKE_CASE__ )[0] if classification_head: SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"](roberta.extract_features(SCREAMING_SNAKE_CASE__ ) ) else: SCREAMING_SNAKE_CASE__ : int = roberta.model(SCREAMING_SNAKE_CASE__ )[0] print(our_output.shape , their_output.shape ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(f'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 SCREAMING_SNAKE_CASE__ : int = torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(SCREAMING_SNAKE_CASE__ ).mkdir(parents=SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_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.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) _lowerCamelCase : Any = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
663
1
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class lowerCamelCase (__lowerCamelCase ): """simple docstring""" @require_torch def A_ ( self : str ) -> List[str]: """simple docstring""" # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched SCREAMING_SNAKE_CASE__ : int = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " SCREAMING_SNAKE_CASE__ : str = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " SCREAMING_SNAKE_CASE__ : Dict = "\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache SCREAMING_SNAKE_CASE__ : Tuple = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task="fill-mask", model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : List[Any] = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files SCREAMING_SNAKE_CASE__ : Dict = "1" SCREAMING_SNAKE_CASE__ : Tuple = subprocess.run(_UpperCAmelCase, env=_UpperCAmelCase, check=_UpperCAmelCase, capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn("success", result.stdout.decode() ) @require_torch def A_ ( self : Dict ) -> Any: """simple docstring""" # python one-liner segments # this must be loaded before socket.socket is monkey-patched SCREAMING_SNAKE_CASE__ : int = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " SCREAMING_SNAKE_CASE__ : Optional[int] = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " SCREAMING_SNAKE_CASE__ : Optional[int] = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache SCREAMING_SNAKE_CASE__ : Dict = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task="fill-mask", model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : Optional[int] = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed SCREAMING_SNAKE_CASE__ : Any = self.get_env() SCREAMING_SNAKE_CASE__ : str = subprocess.run(_UpperCAmelCase, env=_UpperCAmelCase, check=_UpperCAmelCase, capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn("success", result.stdout.decode() ) @require_torch def A_ ( self : int ) -> str: """simple docstring""" # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched SCREAMING_SNAKE_CASE__ : Optional[int] = "\nfrom transformers import BertConfig, BertModel, BertTokenizer\n " SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n " SCREAMING_SNAKE_CASE__ : Any = "\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : Any = [sys.executable, "-c", "\n".join([load, run] )] # should succeed SCREAMING_SNAKE_CASE__ : Dict = self.get_env() SCREAMING_SNAKE_CASE__ : List[str] = subprocess.run(_UpperCAmelCase, env=_UpperCAmelCase, check=_UpperCAmelCase, capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn("success", result.stdout.decode() ) # next emulate no network SCREAMING_SNAKE_CASE__ : Any = [sys.executable, "-c", "\n".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files SCREAMING_SNAKE_CASE__ : Dict = "1" SCREAMING_SNAKE_CASE__ : Dict = subprocess.run(_UpperCAmelCase, env=_UpperCAmelCase, check=_UpperCAmelCase, capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn("success", result.stdout.decode() ) @require_torch def A_ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = "\nfrom transformers import pipeline\n " SCREAMING_SNAKE_CASE__ : Dict = "\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n " SCREAMING_SNAKE_CASE__ : int = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " SCREAMING_SNAKE_CASE__ : List[str] = self.get_env() SCREAMING_SNAKE_CASE__ : Tuple = "1" SCREAMING_SNAKE_CASE__ : Tuple = [sys.executable, "-c", "\n".join([load, mock, run] )] SCREAMING_SNAKE_CASE__ : Optional[Any] = subprocess.run(_UpperCAmelCase, env=_UpperCAmelCase, check=_UpperCAmelCase, capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode, 1, result.stderr ) self.assertIn( "You cannot infer task automatically within `pipeline` when using offline mode", result.stderr.decode().replace("\n", "" ), ) @require_torch def A_ ( self : int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = "\nfrom transformers import AutoModel\n " SCREAMING_SNAKE_CASE__ : List[str] = "\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n " # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : Dict = [sys.executable, "-c", "\n".join([load, run] )] # should succeed SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_env() SCREAMING_SNAKE_CASE__ : Optional[Any] = subprocess.run(_UpperCAmelCase, env=_UpperCAmelCase, check=_UpperCAmelCase, capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn("success", result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files SCREAMING_SNAKE_CASE__ : List[Any] = "1" SCREAMING_SNAKE_CASE__ : Optional[int] = subprocess.run(_UpperCAmelCase, env=_UpperCAmelCase, check=_UpperCAmelCase, capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn("success", result.stdout.decode() )
663
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "Wav2Vec2FeatureExtractor" UpperCAmelCase_ = "AutoTokenizer" def __init__( self : Tuple, _UpperCAmelCase : Dict, _UpperCAmelCase : Tuple ) -> List[str]: """simple docstring""" super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extractor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False @classmethod def A_ ( cls : int, _UpperCAmelCase : Dict, **_UpperCAmelCase : List[Any] ) -> Optional[int]: """simple docstring""" try: return super().from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) except OSError: warnings.warn( F'''Loading a tokenizer inside {cls.__name__} from a config that does not''' " include a `tokenizer_class` attribute is deprecated and will be " "removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`" " attribute to either your `config.json` or `tokenizer_config.json` " "file to suppress this warning: ", _UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaFeatureExtractor.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = WavaVecaCTCTokenizer.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) return cls(feature_extractor=_UpperCAmelCase, tokenizer=_UpperCAmelCase ) def __call__( self : Optional[Any], *_UpperCAmelCase : int, **_UpperCAmelCase : str ) -> Optional[Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) if "raw_speech" in kwargs: warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead." ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("raw_speech" ) else: SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop("audio", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("sampling_rate", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : Tuple = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if audio is not None: SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor(_UpperCAmelCase, *_UpperCAmelCase, sampling_rate=_UpperCAmelCase, **_UpperCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE__ : List[str] = encodings["input_ids"] return inputs def A_ ( self : Optional[Any], *_UpperCAmelCase : List[str], **_UpperCAmelCase : Optional[int] ) -> Optional[int]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("input_features", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop("labels", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : Dict = args[1:] if input_features is not None: SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor.pad(_UpperCAmelCase, *_UpperCAmelCase, **_UpperCAmelCase ) if labels is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.pad(_UpperCAmelCase, **_UpperCAmelCase ) if labels is None: return input_features elif input_features is None: return labels else: SCREAMING_SNAKE_CASE__ : List[str] = labels["input_ids"] return input_features def A_ ( self : Union[str, Any], *_UpperCAmelCase : str, **_UpperCAmelCase : Any ) -> Optional[int]: """simple docstring""" return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Optional[int], *_UpperCAmelCase : Tuple, **_UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) @contextmanager def A_ ( self : Optional[int] ) -> Any: """simple docstring""" warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your audio inputs, or in a separate call." ) SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : int = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extractor SCREAMING_SNAKE_CASE__ : Optional[Any] = False
663
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Tuple = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowerCamelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Tuple = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowerCamelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
663
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[int] = logging.get_logger(__name__) class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "encoder-decoder" UpperCAmelCase_ = True def __init__( self : Tuple, **_UpperCAmelCase : Dict ) -> int: """simple docstring""" super().__init__(**_UpperCAmelCase ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs.pop("encoder" ) SCREAMING_SNAKE_CASE__ : Any = encoder_config.pop("model_type" ) SCREAMING_SNAKE_CASE__ : int = kwargs.pop("decoder" ) SCREAMING_SNAKE_CASE__ : int = decoder_config.pop("model_type" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ : List[str] = AutoConfig.for_model(_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = AutoConfig.for_model(_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = True @classmethod def A_ ( cls : int, _UpperCAmelCase : PretrainedConfig, _UpperCAmelCase : PretrainedConfig, **_UpperCAmelCase : Tuple ) -> PretrainedConfig: """simple docstring""" logger.info("Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" ) SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Optional[Any] = True return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.encoder.to_dict() SCREAMING_SNAKE_CASE__ : List[str] = self.decoder.to_dict() SCREAMING_SNAKE_CASE__ : Any = self.__class__.model_type return output
663
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = '''▁''' _lowerCamelCase : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''monolingual_vocab_file''': '''dict.txt'''} _lowerCamelCase : Dict = { '''vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model''', }, '''monolingual_vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt''', }, } _lowerCamelCase : Optional[Any] = {'''vinai/bartpho-syllable''': 1_0_2_4} class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = ["input_ids", "attention_mask"] def __init__( self : int, _UpperCAmelCase : Dict, _UpperCAmelCase : Tuple, _UpperCAmelCase : Any="<s>", _UpperCAmelCase : List[str]="</s>", _UpperCAmelCase : List[str]="</s>", _UpperCAmelCase : List[Any]="<s>", _UpperCAmelCase : Dict="<unk>", _UpperCAmelCase : Tuple="<pad>", _UpperCAmelCase : int="<mask>", _UpperCAmelCase : Optional[Dict[str, Any]] = None, **_UpperCAmelCase : Any, ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Any = AddedToken(_UpperCAmelCase, lstrip=_UpperCAmelCase, rstrip=_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ) else mask_token SCREAMING_SNAKE_CASE__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCAmelCase, eos_token=_UpperCAmelCase, unk_token=_UpperCAmelCase, sep_token=_UpperCAmelCase, cls_token=_UpperCAmelCase, pad_token=_UpperCAmelCase, mask_token=_UpperCAmelCase, sp_model_kwargs=self.sp_model_kwargs, **_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_file SCREAMING_SNAKE_CASE__ : Optional[int] = monolingual_vocab_file SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_UpperCAmelCase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_UpperCAmelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : Dict = cnt cnt += 1 with open(_UpperCAmelCase, "r", encoding="utf-8" ) as f: for line in f.readlines(): SCREAMING_SNAKE_CASE__ : int = line.strip().split()[0] SCREAMING_SNAKE_CASE__ : Tuple = len(self.fairseq_tokens_to_ids ) if str(_UpperCAmelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : List[Any] = len(self.fairseq_tokens_to_ids ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : int = self.sp_model.serialized_model_proto() return state def __setstate__( self : int, _UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = d # for backward compatibility if not hasattr(self, "sp_model_kwargs" ): SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def A_ ( self : Optional[int], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Any = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : List[str], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None, _UpperCAmelCase : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase, token_ids_a=_UpperCAmelCase, already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1, 1] + ([0] * len(_UpperCAmelCase )) + [1] def A_ ( self : Optional[int], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A_ ( self : Any ) -> List[str]: """simple docstring""" return len(self.fairseq_ids_to_tokens ) def A_ ( self : Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = {self.convert_ids_to_tokens(_UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : Tuple, _UpperCAmelCase : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_UpperCAmelCase, out_type=_UpperCAmelCase ) def A_ ( self : List[str], _UpperCAmelCase : Union[str, Any] ) -> Tuple: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def A_ ( self : List[str], _UpperCAmelCase : str ) -> str: """simple docstring""" return self.fairseq_ids_to_tokens[index] def A_ ( self : Optional[Any], _UpperCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "".join(_UpperCAmelCase ).replace(_UpperCAmelCase, " " ).strip() return out_string def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_UpperCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["monolingual_vocab_file"], ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, _UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCAmelCase, "wb" ) as fi: SCREAMING_SNAKE_CASE__ : int = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _UpperCAmelCase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file, _UpperCAmelCase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_UpperCAmelCase, "w", encoding="utf-8" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F'''{str(_UpperCAmelCase )} \n''' ) return out_vocab_file, out_monolingual_vocab_file
663
1
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = DiTPipeline UpperCAmelCase_ = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS UpperCAmelCase_ = PipelineTesterMixin.required_optional_params - { "latents", "num_images_per_prompt", "callback", "callback_steps", } UpperCAmelCase_ = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS UpperCAmelCase_ = False def A_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = TransformeraDModel( sample_size=1_6, num_layers=2, patch_size=4, attention_head_dim=8, num_attention_heads=2, in_channels=4, out_channels=8, attention_bias=_UpperCAmelCase, activation_fn="gelu-approximate", num_embeds_ada_norm=1_0_0_0, norm_type="ada_norm_zero", norm_elementwise_affine=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = AutoencoderKL() SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler() SCREAMING_SNAKE_CASE__ : List[Any] = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def A_ ( self : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Optional[int]=0 ) -> Dict: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : Dict = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "cpu" SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.pipeline_class(**_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self.get_dummy_inputs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = pipe(**_UpperCAmelCase ).images SCREAMING_SNAKE_CASE__ : str = image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 1_6, 1_6, 3) ) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) SCREAMING_SNAKE_CASE__ : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_UpperCAmelCase, 1E-3 ) def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_UpperCAmelCase, expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available(), reason="XFormers attention is only available with CUDA and `xformers` installed", ) def A_ ( self : int ) -> Tuple: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Dict ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["vase", "umbrella", "white shark", "white wolf"] SCREAMING_SNAKE_CASE__ : List[Any] = pipe.get_label_ids(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe(_UpperCAmelCase, generator=_UpperCAmelCase, num_inference_steps=4_0, output_type="np" ).images for word, image in zip(_UpperCAmelCase, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : str = load_numpy( F'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1E-2 def A_ ( self : Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) SCREAMING_SNAKE_CASE__ : Optional[int] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) SCREAMING_SNAKE_CASE__ : int = ["vase", "umbrella"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe.get_label_ids(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = pipe(_UpperCAmelCase, generator=_UpperCAmelCase, num_inference_steps=2_5, output_type="np" ).images for word, image in zip(_UpperCAmelCase, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" F'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1E-1
663
from random import shuffle import tensorflow as tf from numpy import array def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = int(SCREAMING_SNAKE_CASE__ ) assert noofclusters < len(SCREAMING_SNAKE_CASE__ ) # Find out the dimensionality SCREAMING_SNAKE_CASE__ : List[Any] = len(vectors[0] ) # Will help select random centroids from among the available vectors SCREAMING_SNAKE_CASE__ : List[Any] = list(range(len(SCREAMING_SNAKE_CASE__ ) ) ) shuffle(SCREAMING_SNAKE_CASE__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. SCREAMING_SNAKE_CASE__ : Tuple = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION SCREAMING_SNAKE_CASE__ : List[Any] = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points SCREAMING_SNAKE_CASE__ : Any = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(SCREAMING_SNAKE_CASE__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("float64" , [dim] ) SCREAMING_SNAKE_CASE__ : Dict = [] for centroid in centroids: cent_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) SCREAMING_SNAKE_CASE__ : Tuple = [tf.Variable(0 ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value SCREAMING_SNAKE_CASE__ : Tuple = tf.placeholder("int32" ) SCREAMING_SNAKE_CASE__ : Tuple = [] for assignment in assignments: cluster_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input SCREAMING_SNAKE_CASE__ : int = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors SCREAMING_SNAKE_CASE__ : str = tf.reduce_mean(SCREAMING_SNAKE_CASE__ , 0 ) ##Node for computing Euclidean distances # Placeholders for input SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.placeholder("float" , [dim] ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("float" , [dim] ) SCREAMING_SNAKE_CASE__ : Dict = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.placeholder("float" , [noofclusters] ) SCREAMING_SNAKE_CASE__ : Tuple = tf.argmin(SCREAMING_SNAKE_CASE__ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. SCREAMING_SNAKE_CASE__ : Tuple = tf.initialize_all_variables() # Initialize all variables sess.run(SCREAMING_SNAKE_CASE__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. SCREAMING_SNAKE_CASE__ : Tuple = 1_00 for _ in range(SCREAMING_SNAKE_CASE__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(SCREAMING_SNAKE_CASE__ ) ): SCREAMING_SNAKE_CASE__ : Any = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. SCREAMING_SNAKE_CASE__ : Tuple = [ sess.run(SCREAMING_SNAKE_CASE__ , feed_dict={va: vect, va: sess.run(SCREAMING_SNAKE_CASE__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input SCREAMING_SNAKE_CASE__ : Any = sess.run( SCREAMING_SNAKE_CASE__ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(SCREAMING_SNAKE_CASE__ ): # Collect all the vectors assigned to this cluster SCREAMING_SNAKE_CASE__ : Dict = [ vectors[i] for i in range(len(SCREAMING_SNAKE_CASE__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location SCREAMING_SNAKE_CASE__ : str = sess.run( SCREAMING_SNAKE_CASE__ , feed_dict={mean_input: array(SCREAMING_SNAKE_CASE__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments SCREAMING_SNAKE_CASE__ : int = sess.run(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = sess.run(SCREAMING_SNAKE_CASE__ ) return centroids, assignments
663
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: _lowerCamelCase : Tuple = None _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : Tuple = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase : Optional[int] = { '''vocab_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json''' ), }, } _lowerCamelCase : Optional[int] = { '''moussaKam/mbarthez''': 1_0_2_4, '''moussaKam/barthez''': 1_0_2_4, '''moussaKam/barthez-orangesum-title''': 1_0_2_4, } _lowerCamelCase : Optional[Any] = '''▁''' class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = ["input_ids", "attention_mask"] UpperCAmelCase_ = BarthezTokenizer def __init__( self : Dict, _UpperCAmelCase : List[Any]=None, _UpperCAmelCase : Tuple=None, _UpperCAmelCase : List[str]="<s>", _UpperCAmelCase : Optional[int]="</s>", _UpperCAmelCase : Optional[int]="</s>", _UpperCAmelCase : Union[str, Any]="<s>", _UpperCAmelCase : Optional[Any]="<unk>", _UpperCAmelCase : int="<pad>", _UpperCAmelCase : Dict="<mask>", **_UpperCAmelCase : List[str], ) -> Any: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Dict = AddedToken(_UpperCAmelCase, lstrip=_UpperCAmelCase, rstrip=_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ) else mask_token super().__init__( _UpperCAmelCase, tokenizer_file=_UpperCAmelCase, bos_token=_UpperCAmelCase, eos_token=_UpperCAmelCase, unk_token=_UpperCAmelCase, sep_token=_UpperCAmelCase, cls_token=_UpperCAmelCase, pad_token=_UpperCAmelCase, mask_token=_UpperCAmelCase, **_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : List[Any] = vocab_file SCREAMING_SNAKE_CASE__ : Optional[int] = False if not self.vocab_file else True def A_ ( self : Dict, _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : int = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : List[str], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def A_ ( self : List[Any], _UpperCAmelCase : str, _UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(_UpperCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : int = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCAmelCase ): copyfile(self.vocab_file, _UpperCAmelCase ) return (out_vocab_file,)
663
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) _lowerCamelCase : List[str] = None _lowerCamelCase : Union[str, Any] = { '''7B''': 1_1_0_0_8, '''13B''': 1_3_8_2_4, '''30B''': 1_7_9_2_0, '''65B''': 2_2_0_1_6, '''70B''': 2_8_6_7_2, } _lowerCamelCase : Optional[Any] = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : str=2_56 ) -> int: '''simple docstring''' return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def _a ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ , "r" ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str=True ) -> int: '''simple docstring''' os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , "tmp" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = read_json(os.path.join(SCREAMING_SNAKE_CASE__ , "params.json" ) ) SCREAMING_SNAKE_CASE__ : int = NUM_SHARDS[model_size] SCREAMING_SNAKE_CASE__ : Union[str, Any] = params["n_layers"] SCREAMING_SNAKE_CASE__ : List[str] = params["n_heads"] SCREAMING_SNAKE_CASE__ : Optional[Any] = n_heads // num_shards SCREAMING_SNAKE_CASE__ : str = params["dim"] SCREAMING_SNAKE_CASE__ : List[str] = dim // n_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_0_0_0_0.0 SCREAMING_SNAKE_CASE__ : Tuple = 1.0 / (base ** (torch.arange(0 , SCREAMING_SNAKE_CASE__ , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: SCREAMING_SNAKE_CASE__ : int = params["n_kv_heads"] # for GQA / MQA SCREAMING_SNAKE_CASE__ : Optional[int] = n_heads_per_shard // num_key_value_heads SCREAMING_SNAKE_CASE__ : int = dim // num_key_value_heads else: # compatibility with other checkpoints SCREAMING_SNAKE_CASE__ : Dict = n_heads SCREAMING_SNAKE_CASE__ : str = n_heads_per_shard SCREAMING_SNAKE_CASE__ : Dict = dim # permute for sliced rotary def permute(SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=n_heads , SCREAMING_SNAKE_CASE__ : List[str]=dim , SCREAMING_SNAKE_CASE__ : Dict=dim ): return w.view(SCREAMING_SNAKE_CASE__ , dima // n_heads // 2 , 2 , SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'''Fetching all parameters from the checkpoint at {input_base_path}.''' ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) SCREAMING_SNAKE_CASE__ : Dict = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , "consolidated.00.pth" ) , map_location="cpu" ) else: # Sharded SCREAMING_SNAKE_CASE__ : List[Any] = [ torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , f'''consolidated.{i:02d}.pth''' ) , map_location="cpu" ) for i in range(SCREAMING_SNAKE_CASE__ ) ] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : List[str] = {"weight_map": {}} for layer_i in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded SCREAMING_SNAKE_CASE__ : List[Any] = { f'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wq.weight'''] ), f'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wk.weight'''] ), f'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[f'''layers.{layer_i}.attention.wv.weight'''], f'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[f'''layers.{layer_i}.attention.wo.weight'''], f'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w1.weight'''], f'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w2.weight'''], f'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w3.weight'''], f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[f'''layers.{layer_i}.attention_norm.weight'''], f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[f'''layers.{layer_i}.ffn_norm.weight'''], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. SCREAMING_SNAKE_CASE__ : Any = { f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.attention_norm.weight''' ].clone(), f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.ffn_norm.weight''' ].clone(), } SCREAMING_SNAKE_CASE__ : int = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wq.weight'''].view(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : Tuple = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wk.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wv.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = torch.cat( [loaded[i][f'''layers.{layer_i}.attention.wo.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : int = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) SCREAMING_SNAKE_CASE__ : List[str] = inv_freq for k, v in state_dict.items(): SCREAMING_SNAKE_CASE__ : str = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded SCREAMING_SNAKE_CASE__ : List[str] = { "model.embed_tokens.weight": loaded["tok_embeddings.weight"], "model.norm.weight": loaded["norm.weight"], "lm_head.weight": loaded["output.weight"], } else: SCREAMING_SNAKE_CASE__ : Optional[Any] = { "model.norm.weight": loaded[0]["norm.weight"], "model.embed_tokens.weight": torch.cat( [loaded[i]["tok_embeddings.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ), "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ), } for k, v in state_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[int] = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Write configs SCREAMING_SNAKE_CASE__ : Optional[Any] = {"total_size": param_count * 2} write_json(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , "pytorch_model.bin.index.json" ) ) SCREAMING_SNAKE_CASE__ : List[str] = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1 SCREAMING_SNAKE_CASE__ : Dict = params["multiple_of"] if "multiple_of" in params else 2_56 SCREAMING_SNAKE_CASE__ : Dict = LlamaConfig( hidden_size=SCREAMING_SNAKE_CASE__ , intermediate_size=compute_intermediate_size(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , num_attention_heads=params["n_heads"] , num_hidden_layers=params["n_layers"] , rms_norm_eps=params["norm_eps"] , num_key_value_heads=SCREAMING_SNAKE_CASE__ , ) config.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("Loading the checkpoint in a Llama model." ) SCREAMING_SNAKE_CASE__ : int = LlamaForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa , low_cpu_mem_usage=SCREAMING_SNAKE_CASE__ ) # Avoid saving this as part of the config. del model.config._name_or_path print("Saving in the Transformers format." ) model.save_pretrained(SCREAMING_SNAKE_CASE__ , safe_serialization=SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(f'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer_class(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() parser.add_argument( "--input_dir" , help="Location of LLaMA weights, which contains tokenizer.model and model folders" , ) parser.add_argument( "--model_size" , choices=["7B", "7Bf", "13B", "13Bf", "30B", "65B", "70B", "70Bf", "tokenizer_only"] , ) parser.add_argument( "--output_dir" , help="Location to write HF model and tokenizer" , ) parser.add_argument("--safe_serialization" , type=SCREAMING_SNAKE_CASE__ , help="Whether or not to save using `safetensors`." ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(args.input_dir , "tokenizer.model" ) write_tokenizer(args.output_dir , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
663
1
_lowerCamelCase : Union[str, Any] = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def _a ( SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> list[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE__ : Optional[Any] = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE__ : Tuple = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE__ : Optional[int] = path[-1] if node not in explored: SCREAMING_SNAKE_CASE__ : Dict = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE__ : List[Any] = list(SCREAMING_SNAKE_CASE__ ) new_path.append(SCREAMING_SNAKE_CASE__ ) queue.append(SCREAMING_SNAKE_CASE__ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(SCREAMING_SNAKE_CASE__ ) # in case there's no path between the 2 nodes return [] def _a ( SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> int: '''simple docstring''' if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = [start] SCREAMING_SNAKE_CASE__ : str = set(SCREAMING_SNAKE_CASE__ ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE__ : int = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE__ : Tuple = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE__ : Optional[int] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(SCREAMING_SNAKE_CASE__ ) queue.append(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
663
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = GPTaTokenizer UpperCAmelCase_ = GPTaTokenizerFast UpperCAmelCase_ = True UpperCAmelCase_ = {"add_prefix_space": True} UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : Any = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] SCREAMING_SNAKE_CASE__ : int = dict(zip(_UpperCAmelCase, range(len(_UpperCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE__ : str = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] SCREAMING_SNAKE_CASE__ : Any = {"unk_token": "<unk>"} SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file, "w", encoding="utf-8" ) as fp: fp.write(json.dumps(_UpperCAmelCase ) + "\n" ) with open(self.merges_file, "w", encoding="utf-8" ) as fp: fp.write("\n".join(_UpperCAmelCase ) ) def A_ ( self : Tuple, **_UpperCAmelCase : str ) -> str: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : int, **_UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : Tuple, _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = "lower newer" SCREAMING_SNAKE_CASE__ : List[Any] = "lower newer" return input_text, output_text def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Tuple = "lower newer" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] SCREAMING_SNAKE_CASE__ : Dict = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Dict = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Dict ) -> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = "lower newer" # Testing tokenization SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE__ : Tuple = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing the unknown token SCREAMING_SNAKE_CASE__ : Dict = tokens + [rust_tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : str = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Tuple, *_UpperCAmelCase : List[Any], **_UpperCAmelCase : Union[str, Any] ) -> Optional[int]: """simple docstring""" # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def A_ ( self : Optional[Any], _UpperCAmelCase : int=1_5 ) -> List[str]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Any = self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) # Simple input SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : List[str] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Any = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : List[Any] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) def A_ ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = GPTaTokenizer.from_pretrained(self.tmpdirname, pad_token="<pad>" ) # Simple input SCREAMING_SNAKE_CASE__ : Union[str, Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Dict = ["This is a simple input looooooooong", "This is a simple input"] SCREAMING_SNAKE_CASE__ : List[str] = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : int = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding="max_length", max_length=3_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(*_UpperCAmelCase, padding="max_length", max_length=6_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1], 3_0 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1], 3_3 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1], 6_0 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1], 5_2 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "$$$" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer.from_pretrained(self.tmpdirname, bos_token=_UpperCAmelCase, add_bos_token=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(_UpperCAmelCase ) self.assertEqual(out_s.input_ids[0], _UpperCAmelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.decode(out_s.input_ids ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], _UpperCAmelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def A_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" pass def A_ ( self : Dict ) -> str: """simple docstring""" # TODO: change to self.get_tokenizers() when the fast version is implemented SCREAMING_SNAKE_CASE__ : Any = [self.get_tokenizer(do_lower_case=_UpperCAmelCase, add_bos_token=_UpperCAmelCase )] for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ : List[Any] = "Encode this." SCREAMING_SNAKE_CASE__ : Optional[Any] = "This one too please." SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) encoded_sequence += tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode_plus( _UpperCAmelCase, _UpperCAmelCase, add_special_tokens=_UpperCAmelCase, return_special_tokens_mask=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(_UpperCAmelCase ), len(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(_UpperCAmelCase ) ] SCREAMING_SNAKE_CASE__ : List[Any] = [x for x in filtered_sequence if x is not None] self.assertEqual(_UpperCAmelCase, _UpperCAmelCase ) @require_tokenizers class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Optional[Any] ) -> int: """simple docstring""" # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("test_opt" ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("./test_opt" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", use_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = "A photo of a cat" SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode( _UpperCAmelCase, ) # Same as above self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) @unittest.skip("This test is failing because of a bug in the fast tokenizer" ) def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = "bos" SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.get_vocab()["bos"] SCREAMING_SNAKE_CASE__ : Tuple = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode( _UpperCAmelCase, ) # We changed the bos token self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("./tok" ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained("./tok" ) self.assertTrue(tokenizer.is_fast ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] )
663
1
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--txt2img_unclip''', default='''kakaobrain/karlo-v1-alpha''', type=str, required=False, help='''The pretrained txt2img unclip.''', ) _lowerCamelCase : int = parser.parse_args() _lowerCamelCase : Any = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) _lowerCamelCase : Tuple = CLIPImageProcessor() _lowerCamelCase : Any = CLIPVisionModelWithProjection.from_pretrained('''openai/clip-vit-large-patch14''') _lowerCamelCase : Dict = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
663
from functools import lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> set: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(SCREAMING_SNAKE_CASE__ ) if n > 1: factors.add(SCREAMING_SNAKE_CASE__ ) return factors @lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' return len(unique_prime_factors(SCREAMING_SNAKE_CASE__ ) ) def _a ( SCREAMING_SNAKE_CASE__ : list ) -> bool: '''simple docstring''' return len(set(SCREAMING_SNAKE_CASE__ ) ) in (0, 1) def _a ( SCREAMING_SNAKE_CASE__ : int ) -> list: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 2 while True: # Increment each value of a generated range SCREAMING_SNAKE_CASE__ : List[str] = [base + i for i in range(SCREAMING_SNAKE_CASE__ )] # Run elements through out unique_prime_factors function # Append our target number to the end. SCREAMING_SNAKE_CASE__ : Tuple = [upf_len(SCREAMING_SNAKE_CASE__ ) for x in group] checker.append(SCREAMING_SNAKE_CASE__ ) # If all numbers in the list are equal, return the group variable. if equality(SCREAMING_SNAKE_CASE__ ): return group # Increment our base variable by 1 base += 1 def _a ( SCREAMING_SNAKE_CASE__ : int = 4 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = run(SCREAMING_SNAKE_CASE__ ) return results[0] if len(SCREAMING_SNAKE_CASE__ ) else None if __name__ == "__main__": print(solution())
663
1
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 _lowerCamelCase : Any = logging.get_logger(__name__) class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = 42 UpperCAmelCase_ = None @staticmethod def A_ ( ) -> str: """simple docstring""" raise NotImplementedError def A_ ( self : Dict, _UpperCAmelCase : Tuple, _UpperCAmelCase : int, _UpperCAmelCase : str, **_UpperCAmelCase : List[str] ) -> List[Any]: """simple docstring""" raise NotImplementedError def A_ ( self : List[str], _UpperCAmelCase : Dict ) -> str: """simple docstring""" raise NotImplementedError def A_ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" 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 : Optional[int] ) -> Optional[Any]: """simple docstring""" return F'''`pip install {cls.pip_package or cls.name}`''' class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "optuna" @staticmethod def A_ ( ) -> Optional[Any]: """simple docstring""" return is_optuna_available() def A_ ( self : List[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : int, _UpperCAmelCase : str, **_UpperCAmelCase : Union[str, Any] ) -> List[str]: """simple docstring""" return run_hp_search_optuna(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Optional[int], _UpperCAmelCase : int ) -> Dict: """simple docstring""" return default_hp_space_optuna(_UpperCAmelCase ) class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "ray" UpperCAmelCase_ = "'ray[tune]'" @staticmethod def A_ ( ) -> int: """simple docstring""" return is_ray_available() def A_ ( self : Dict, _UpperCAmelCase : List[str], _UpperCAmelCase : int, _UpperCAmelCase : str, **_UpperCAmelCase : str ) -> Any: """simple docstring""" return run_hp_search_ray(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : str, _UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" return default_hp_space_ray(_UpperCAmelCase ) class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "sigopt" @staticmethod def A_ ( ) -> str: """simple docstring""" return is_sigopt_available() def A_ ( self : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int, _UpperCAmelCase : str, **_UpperCAmelCase : Tuple ) -> Tuple: """simple docstring""" return run_hp_search_sigopt(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Any, _UpperCAmelCase : List[Any] ) -> Optional[int]: """simple docstring""" return default_hp_space_sigopt(_UpperCAmelCase ) class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "wandb" @staticmethod def A_ ( ) -> Optional[Any]: """simple docstring""" return is_wandb_available() def A_ ( self : int, _UpperCAmelCase : str, _UpperCAmelCase : int, _UpperCAmelCase : str, **_UpperCAmelCase : Tuple ) -> Optional[int]: """simple docstring""" return run_hp_search_wandb(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Union[str, Any], _UpperCAmelCase : List[str] ) -> List[Any]: """simple docstring""" return default_hp_space_wandb(_UpperCAmelCase ) _lowerCamelCase : Optional[int] = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def _a ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(SCREAMING_SNAKE_CASE__ ) > 0: SCREAMING_SNAKE_CASE__ : int = available_backends[0].name if len(SCREAMING_SNAKE_CASE__ ) > 1: logger.info( f'''{len(SCREAMING_SNAKE_CASE__ )} 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() ) )
663
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" @require_torch def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = pipeline( task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused" ) SCREAMING_SNAKE_CASE__ : int = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : int = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> Dict: """simple docstring""" pass @slow @require_torch def A_ ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pipeline( task="zero-shot-audio-classification", model="laion/clap-htsat-unfused", ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ : List[str] = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Optional[Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier( [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5 ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> List[str]: """simple docstring""" pass
663
1
from __future__ import annotations from collections.abc import Callable _lowerCamelCase : Optional[Any] = list[list[float | int]] def _a ( SCREAMING_SNAKE_CASE__ : Matrix , SCREAMING_SNAKE_CASE__ : Matrix ) -> Matrix: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = len(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(SCREAMING_SNAKE_CASE__ )] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : float for row in range(SCREAMING_SNAKE_CASE__ ): for col in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[Any] = matrix[row][col] SCREAMING_SNAKE_CASE__ : List[Any] = vector[row][0] SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 while row < size and col < size: # pivoting SCREAMING_SNAKE_CASE__ : Optional[Any] = max((abs(augmented[rowa][col] ), rowa) for rowa in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : str = augmented[rowa][col] / augmented[row][col] SCREAMING_SNAKE_CASE__ : int = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , SCREAMING_SNAKE_CASE__ ): for row in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[Any] = augmented[row][col] / augmented[col][col] for cola in range(SCREAMING_SNAKE_CASE__ , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(SCREAMING_SNAKE_CASE__ ) ] def _a ( SCREAMING_SNAKE_CASE__ : list[int] ) -> Callable[[int], int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = len(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Matrix = [[0 for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ )] SCREAMING_SNAKE_CASE__ : Matrix = [[0] for _ in range(SCREAMING_SNAKE_CASE__ )] SCREAMING_SNAKE_CASE__ : Matrix SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int for x_val, y_val in enumerate(SCREAMING_SNAKE_CASE__ ): for col in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = (x_val + 1) ** (size - col - 1) SCREAMING_SNAKE_CASE__ : Tuple = y_val SCREAMING_SNAKE_CASE__ : Union[str, Any] = solve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def interpolated_func(SCREAMING_SNAKE_CASE__ : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(SCREAMING_SNAKE_CASE__ ) ) return interpolated_func def _a ( SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def _a ( SCREAMING_SNAKE_CASE__ : Callable[[int], int] = question_function , SCREAMING_SNAKE_CASE__ : int = 10 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[int] = [func(SCREAMING_SNAKE_CASE__ ) for x_val in range(1 , order + 1 )] SCREAMING_SNAKE_CASE__ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : Callable[[int], int] SCREAMING_SNAKE_CASE__ : int for poly in polynomials: SCREAMING_SNAKE_CASE__ : Tuple = 1 while func(SCREAMING_SNAKE_CASE__ ) == poly(SCREAMING_SNAKE_CASE__ ): x_val += 1 ret += poly(SCREAMING_SNAKE_CASE__ ) return ret if __name__ == "__main__": print(f"{solution() = }")
663
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase : List[str] = 2_0_0 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase : Any = 5_0 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase : str = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1_0_0_0)) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, float]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = len([g for position, g in enumerate(SCREAMING_SNAKE_CASE__ ) if g == main_target[position]] ) return (item, float(SCREAMING_SNAKE_CASE__ )) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) SCREAMING_SNAKE_CASE__ : Tuple = parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE__ : str = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = list(SCREAMING_SNAKE_CASE__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE__ : Tuple = random.choice(SCREAMING_SNAKE_CASE__ ) return "".join(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : tuple[str, float] , SCREAMING_SNAKE_CASE__ : list[tuple[str, float]] , SCREAMING_SNAKE_CASE__ : list[str] , ) -> list[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE__ : List[str] = int(parent_a[1] * 1_00 ) + 1 SCREAMING_SNAKE_CASE__ : Tuple = 10 if child_n >= 10 else child_n for _ in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = population_score[random.randint(0 , SCREAMING_SNAKE_CASE__ )][0] SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = crossover(parent_a[0] , SCREAMING_SNAKE_CASE__ ) # Append new string to the population list. pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) return pop def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] , SCREAMING_SNAKE_CASE__ : bool = True ) -> tuple[int, int, str]: '''simple docstring''' if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE__ : str = f'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE__ : Optional[int] = sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE__ : Dict = f'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Generate random starting population. SCREAMING_SNAKE_CASE__ : List[Any] = [] for _ in range(SCREAMING_SNAKE_CASE__ ): population.append("".join([random.choice(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(SCREAMING_SNAKE_CASE__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE__ : int = [evaluate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE__ : List[str] = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[1] , reverse=SCREAMING_SNAKE_CASE__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f'''\nGeneration: {generation}''' f'''\nTotal Population:{total_population}''' f'''\nBest score: {population_score[0][1]}''' f'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE__ : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(SCREAMING_SNAKE_CASE__ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ (item, score / len(SCREAMING_SNAKE_CASE__ )) for item, score in population_score ] # This is selection for i in range(SCREAMING_SNAKE_CASE__ ): population.extend(select(population_score[int(SCREAMING_SNAKE_CASE__ )] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(SCREAMING_SNAKE_CASE__ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase : Dict = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) _lowerCamelCase : Tuple = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = basic(target_str, genes_list) print( f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
663
1
class lowerCamelCase : """simple docstring""" def __init__( self : List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = {} def A_ ( self : str, _UpperCAmelCase : List[Any] ) -> Any: """simple docstring""" if vertex not in self.adjacency: SCREAMING_SNAKE_CASE__ : Optional[Any] = {} self.num_vertices += 1 def A_ ( self : Any, _UpperCAmelCase : List[Any], _UpperCAmelCase : Any, _UpperCAmelCase : Any ) -> Dict: """simple docstring""" self.add_vertex(_UpperCAmelCase ) self.add_vertex(_UpperCAmelCase ) if head == tail: return SCREAMING_SNAKE_CASE__ : Optional[int] = weight SCREAMING_SNAKE_CASE__ : Optional[Any] = weight def A_ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_edges() for edge in edges: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = edge edges.remove((tail, head, weight) ) for i in range(len(_UpperCAmelCase ) ): SCREAMING_SNAKE_CASE__ : str = list(edges[i] ) edges.sort(key=lambda _UpperCAmelCase : e[2] ) for i in range(len(_UpperCAmelCase ) - 1 ): if edges[i][2] >= edges[i + 1][2]: SCREAMING_SNAKE_CASE__ : Optional[Any] = edges[i][2] + 1 for edge in edges: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = edge SCREAMING_SNAKE_CASE__ : int = weight SCREAMING_SNAKE_CASE__ : str = weight def __str__( self : Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = "" for tail in self.adjacency: for head in self.adjacency[tail]: SCREAMING_SNAKE_CASE__ : str = self.adjacency[head][tail] string += F'''{head} -> {tail} == {weight}\n''' return string.rstrip("\n" ) def A_ ( self : Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def A_ ( self : List[str] ) -> List[Any]: """simple docstring""" return self.adjacency.keys() @staticmethod def A_ ( _UpperCAmelCase : Union[str, Any]=None, _UpperCAmelCase : Union[str, Any]=None ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = Graph() if vertices is None: SCREAMING_SNAKE_CASE__ : Dict = [] if edges is None: SCREAMING_SNAKE_CASE__ : List[str] = [] for vertex in vertices: g.add_vertex(_UpperCAmelCase ) for edge in edges: g.add_edge(*_UpperCAmelCase ) return g class lowerCamelCase : """simple docstring""" def __init__( self : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = {} SCREAMING_SNAKE_CASE__ : List[Any] = {} def __len__( self : List[str] ) -> Union[str, Any]: """simple docstring""" return len(self.parent ) def A_ ( self : Dict, _UpperCAmelCase : Any ) -> List[Any]: """simple docstring""" if item in self.parent: return self.find(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = item SCREAMING_SNAKE_CASE__ : int = 0 return item def A_ ( self : Optional[int], _UpperCAmelCase : List[Any] ) -> Optional[int]: """simple docstring""" if item not in self.parent: return self.make_set(_UpperCAmelCase ) if item != self.parent[item]: SCREAMING_SNAKE_CASE__ : Optional[int] = self.find(self.parent[item] ) return self.parent[item] def A_ ( self : Any, _UpperCAmelCase : List[Any], _UpperCAmelCase : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.find(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.find(_UpperCAmelCase ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: SCREAMING_SNAKE_CASE__ : Optional[Any] = roota return roota if self.rank[roota] < self.rank[roota]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 SCREAMING_SNAKE_CASE__ : str = roota return roota return None @staticmethod def A_ ( _UpperCAmelCase : Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = graph.num_vertices SCREAMING_SNAKE_CASE__ : Optional[Any] = Graph.UnionFind() SCREAMING_SNAKE_CASE__ : Tuple = [] while num_components > 1: SCREAMING_SNAKE_CASE__ : str = {} for vertex in graph.get_vertices(): SCREAMING_SNAKE_CASE__ : Optional[Any] = -1 SCREAMING_SNAKE_CASE__ : str = graph.get_edges() for edge in edges: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = edge edges.remove((tail, head, weight) ) for edge in edges: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = edge SCREAMING_SNAKE_CASE__ : Optional[int] = union_find.find(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = union_find.find(_UpperCAmelCase ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: SCREAMING_SNAKE_CASE__ : Optional[int] = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: SCREAMING_SNAKE_CASE__ : List[Any] = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = cheap_edge[vertex] if union_find.find(_UpperCAmelCase ) != union_find.find(_UpperCAmelCase ): union_find.union(_UpperCAmelCase, _UpperCAmelCase ) mst_edges.append(cheap_edge[vertex] ) SCREAMING_SNAKE_CASE__ : Tuple = num_components - 1 SCREAMING_SNAKE_CASE__ : Tuple = Graph.build(edges=_UpperCAmelCase ) return mst
663
from collections.abc import Callable import numpy as np def _a ( SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = int(np.ceil((x_end - xa) / step_size ) ) SCREAMING_SNAKE_CASE__ : Tuple = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE__ : Tuple = ya SCREAMING_SNAKE_CASE__ : Dict = xa for k in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = y[k] + step_size * ode_func(SCREAMING_SNAKE_CASE__ , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
663
1
import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": _lowerCamelCase : List[str] = argparse.ArgumentParser( description=( '''Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned''' ''' Distillation''' ) ) parser.add_argument('''--model_type''', default='''bert''', choices=['''bert''']) parser.add_argument('''--model_name''', default='''bert-base-uncased''', type=str) parser.add_argument('''--dump_checkpoint''', default='''serialization_dir/tf_bert-base-uncased_0247911.pth''', type=str) parser.add_argument('''--vocab_transform''', action='''store_true''') _lowerCamelCase : List[Any] = parser.parse_args() if args.model_type == "bert": _lowerCamelCase : Optional[Any] = BertForMaskedLM.from_pretrained(args.model_name) _lowerCamelCase : Union[str, Any] = '''bert''' else: raise ValueError('''args.model_type should be "bert".''') _lowerCamelCase : Optional[Any] = model.state_dict() _lowerCamelCase : Tuple = {} for w in ["word_embeddings", "position_embeddings"]: _lowerCamelCase : Optional[int] = state_dict[f"{prefix}.embeddings.{w}.weight"] for w in ["weight", "bias"]: _lowerCamelCase : Optional[Any] = state_dict[f"{prefix}.embeddings.LayerNorm.{w}"] _lowerCamelCase : str = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: for w in ["weight", "bias"]: _lowerCamelCase : List[str] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}" ] _lowerCamelCase : Union[str, Any] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}" ] _lowerCamelCase : Union[str, Any] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}" ] _lowerCamelCase : List[Any] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}" ] _lowerCamelCase : List[str] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}" ] _lowerCamelCase : Optional[Any] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}" ] _lowerCamelCase : Tuple = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}" ] _lowerCamelCase : Optional[Any] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}" ] std_idx += 1 _lowerCamelCase : int = state_dict['''cls.predictions.decoder.weight'''] _lowerCamelCase : str = state_dict['''cls.predictions.bias'''] if args.vocab_transform: for w in ["weight", "bias"]: _lowerCamelCase : str = state_dict[f"cls.predictions.transform.dense.{w}"] _lowerCamelCase : List[str] = state_dict[f"cls.predictions.transform.LayerNorm.{w}"] print(f"N layers selected for distillation: {std_idx}") print(f"Number of params transferred for distillation: {len(compressed_sd.keys())}") print(f"Save transferred checkpoint to {args.dump_checkpoint}.") torch.save(compressed_sd, args.dump_checkpoint)
663
def _a ( SCREAMING_SNAKE_CASE__ : List[Any]=2_81_23 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i SCREAMING_SNAKE_CASE__ : int = set() SCREAMING_SNAKE_CASE__ : Any = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(SCREAMING_SNAKE_CASE__ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
663
1
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 _lowerCamelCase : List[Any] = re.compile(r'''\s+''') def _a ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return {"hash": hashlib.mda(re.sub(SCREAMING_SNAKE_CASE__ , "" , example["content"] ).encode("utf-8" ) ).hexdigest()} def _a ( SCREAMING_SNAKE_CASE__ : int ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [len(SCREAMING_SNAKE_CASE__ ) for line in example["content"].splitlines()] return {"line_mean": np.mean(SCREAMING_SNAKE_CASE__ ), "line_max": max(SCREAMING_SNAKE_CASE__ )} def _a ( SCREAMING_SNAKE_CASE__ : str ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = np.mean([c.isalnum() for c in example["content"]] ) return {"alpha_frac": alpha_frac} def _a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any ) -> Any: '''simple docstring''' if example["hash"] in uniques: uniques.remove(example["hash"] ) return True else: return False def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str]=5 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = ["auto-generated", "autogenerated", "automatically generated"] SCREAMING_SNAKE_CASE__ : int = example["content"].splitlines() for _, line in zip(range(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def _a ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str=5 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.0_5 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = ["unit tests", "test file", "configuration file"] SCREAMING_SNAKE_CASE__ : Tuple = example["content"].splitlines() SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : int = 0 # first test for _, line in zip(range(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test SCREAMING_SNAKE_CASE__ : Any = example["content"].count("\n" ) SCREAMING_SNAKE_CASE__ : Any = 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 _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ["def ", "class ", "for ", "while "] SCREAMING_SNAKE_CASE__ : List[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 _a ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = example["content"].splitlines() SCREAMING_SNAKE_CASE__ : List[str] = 0 for line in lines: counter += line.lower().count("=" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def _a ( SCREAMING_SNAKE_CASE__ : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer(example["content"] , truncation=SCREAMING_SNAKE_CASE__ )["input_ids"] SCREAMING_SNAKE_CASE__ : List[str] = len(example["content"] ) / len(SCREAMING_SNAKE_CASE__ ) return {"ratio": ratio} def _a ( SCREAMING_SNAKE_CASE__ : Any ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = {} results.update(get_hash(SCREAMING_SNAKE_CASE__ ) ) results.update(line_stats(SCREAMING_SNAKE_CASE__ ) ) results.update(alpha_stats(SCREAMING_SNAKE_CASE__ ) ) results.update(char_token_ratio(SCREAMING_SNAKE_CASE__ ) ) results.update(is_autogenerated(SCREAMING_SNAKE_CASE__ ) ) results.update(is_config_or_test(SCREAMING_SNAKE_CASE__ ) ) results.update(has_no_keywords(SCREAMING_SNAKE_CASE__ ) ) results.update(has_few_assignments(SCREAMING_SNAKE_CASE__ ) ) return results def _a ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' if not check_uniques(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): 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 _a ( SCREAMING_SNAKE_CASE__ : Any ) -> Dict: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ , "rb" ) as f_in: with gzip.open(str(SCREAMING_SNAKE_CASE__ ) + ".gz" , "wb" , compresslevel=6 ) as f_out: shutil.copyfileobj(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) os.unlink(SCREAMING_SNAKE_CASE__ ) # Settings _lowerCamelCase : Tuple = HfArgumentParser(PreprocessingArguments) _lowerCamelCase : int = parser.parse_args() if args.num_workers is None: _lowerCamelCase : Optional[int] = multiprocessing.cpu_count() _lowerCamelCase : Optional[int] = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset _lowerCamelCase : Dict = time.time() _lowerCamelCase : Union[str, Any] = load_dataset(args.dataset_name, split='''train''') print(f"Time to load dataset: {time.time()-t_start:.2f}") # Run preprocessing _lowerCamelCase : Union[str, Any] = time.time() _lowerCamelCase : Dict = ds.map(preprocess, num_proc=args.num_workers) print(f"Time to preprocess dataset: {time.time()-t_start:.2f}") # Deduplicate hashes _lowerCamelCase : Optional[Any] = set(ds.unique('''hash''')) _lowerCamelCase : Any = len(uniques) / len(ds) print(f"Fraction of duplicates: {1-frac:.2%}") # Deduplicate data and apply heuristics _lowerCamelCase : Optional[int] = time.time() _lowerCamelCase : Union[str, Any] = 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: _lowerCamelCase : Dict = time.time() _lowerCamelCase , _lowerCamelCase : Optional[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 _lowerCamelCase : List[Any] = 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) _lowerCamelCase : Union[str, Any] = output_dir / '''data''' data_dir.mkdir(exist_ok=True) _lowerCamelCase : int = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): _lowerCamelCase : Tuple = str(data_dir / f"file-{file_number+1:012}.json") _lowerCamelCase : Dict = 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}")
663
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase : Optional[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = ['''MobileViTFeatureExtractor'''] _lowerCamelCase : List[str] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[Any] = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _lowerCamelCase : Optional[Any] = version.parse(importlib_metadata.version('''nltk''')) if NLTK_VERSION >= version.Version('''3.6.4'''): from nltk import word_tokenize _lowerCamelCase : Optional[Any] = '''\ @inproceedings{banarjee2005, title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments}, author = {Banerjee, Satanjeev and Lavie, Alon}, booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization}, month = jun, year = {2005}, address = {Ann Arbor, Michigan}, publisher = {Association for Computational Linguistics}, url = {https://www.aclweb.org/anthology/W05-0909}, pages = {65--72}, } ''' _lowerCamelCase : str = '''\ METEOR, an automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations. Unigrams can be matched based on their surface forms, stemmed forms, and meanings; furthermore, METEOR can be easily extended to include more advanced matching strategies. Once all generalized unigram matches between the two strings have been found, METEOR computes a score for this matching using a combination of unigram-precision, unigram-recall, and a measure of fragmentation that is designed to directly capture how well-ordered the matched words in the machine translation are in relation to the reference. METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic data and 0.331 on the Chinese data. This is shown to be an improvement on using simply unigram-precision, unigram-recall and their harmonic F1 combination. ''' _lowerCamelCase : int = ''' Computes METEOR score of translated segments against one or more references. Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. alpha: Parameter for controlling relative weights of precision and recall. default: 0.9 beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3 gamma: Relative weight assigned to fragmentation penalty. default: 0.5 Returns: \'meteor\': meteor score. Examples: >>> meteor = datasets.load_metric(\'meteor\') >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"] >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"] >>> results = meteor.compute(predictions=predictions, references=references) >>> print(round(results["meteor"], 4)) 0.6944 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase (datasets.Metric ): """simple docstring""" def A_ ( self : List[Any] ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": datasets.Value("string", id="sequence" ), "references": datasets.Value("string", id="sequence" ), } ), codebase_urls=["https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"], reference_urls=[ "https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score", "https://en.wikipedia.org/wiki/METEOR", ], ) def A_ ( self : int, _UpperCAmelCase : List[Any] ) -> Dict: """simple docstring""" import nltk nltk.download("wordnet" ) if NLTK_VERSION >= version.Version("3.6.5" ): nltk.download("punkt" ) if NLTK_VERSION >= version.Version("3.6.6" ): nltk.download("omw-1.4" ) def A_ ( self : Dict, _UpperCAmelCase : List[str], _UpperCAmelCase : Optional[int], _UpperCAmelCase : List[Any]=0.9, _UpperCAmelCase : int=3, _UpperCAmelCase : int=0.5 ) -> Tuple: """simple docstring""" if NLTK_VERSION >= version.Version("3.6.5" ): SCREAMING_SNAKE_CASE__ : Any = [ meteor_score.single_meteor_score( word_tokenize(_UpperCAmelCase ), word_tokenize(_UpperCAmelCase ), alpha=_UpperCAmelCase, beta=_UpperCAmelCase, gamma=_UpperCAmelCase ) for ref, pred in zip(_UpperCAmelCase, _UpperCAmelCase ) ] else: SCREAMING_SNAKE_CASE__ : int = [ meteor_score.single_meteor_score(_UpperCAmelCase, _UpperCAmelCase, alpha=_UpperCAmelCase, beta=_UpperCAmelCase, gamma=_UpperCAmelCase ) for ref, pred in zip(_UpperCAmelCase, _UpperCAmelCase ) ] return {"meteor": np.mean(_UpperCAmelCase )}
663
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = BlenderbotSmallConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Optional[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : Optional[int]=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : List[Any]=True, _UpperCAmelCase : Union[str, Any]=False, _UpperCAmelCase : str=9_9, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Any=2, _UpperCAmelCase : Any=4, _UpperCAmelCase : List[Any]=3_7, _UpperCAmelCase : Dict=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=2_0, _UpperCAmelCase : int=2, _UpperCAmelCase : Union[str, Any]=1, _UpperCAmelCase : List[str]=0, ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = eos_token_id SCREAMING_SNAKE_CASE__ : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE__ : List[Any] = bos_token_id def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Dict = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Any = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : str = prepare_blenderbot_small_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFBlenderbotSmallModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Optional[Any] = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : List[str] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : Tuple = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Dict = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : int = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Any = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Tuple = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : Tuple = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) UpperCAmelCase_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFBlenderbotSmallForConditionalGeneration, "feature-extraction": TFBlenderbotSmallModel, "summarization": TFBlenderbotSmallForConditionalGeneration, "text2text-generation": TFBlenderbotSmallForConditionalGeneration, "translation": TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFBlenderbotSmallModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[int] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Any ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like " " i'm going to throw up.\nand why is that?" ] UpperCAmelCase_ = "facebook/blenderbot_small-90M" @cached_property def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def A_ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
663
1
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCamelCase : """simple docstring""" @staticmethod def A_ ( *_UpperCAmelCase : str, **_UpperCAmelCase : Dict ) -> Optional[Any]: """simple docstring""" pass def _a ( SCREAMING_SNAKE_CASE__ : Image ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _a ( SCREAMING_SNAKE_CASE__ : Image ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = np.array(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = npimg.shape return {"hash": hashimage(SCREAMING_SNAKE_CASE__ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCAmelCase_ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def A_ ( self : str, _UpperCAmelCase : List[Any], _UpperCAmelCase : str, _UpperCAmelCase : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = MaskGenerationPipeline(model=_UpperCAmelCase, image_processor=_UpperCAmelCase ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def A_ ( self : Optional[Any], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Union[str, Any] ) -> Any: """simple docstring""" pass @require_tf @unittest.skip("Image segmentation not implemented in TF" ) def A_ ( self : List[str] ) -> List[Any]: """simple docstring""" pass @slow @require_torch def A_ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = pipeline("mask-generation", model="facebook/sam-vit-huge" ) SCREAMING_SNAKE_CASE__ : Dict = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", points_per_batch=2_5_6 ) # Shortening by hashing SCREAMING_SNAKE_CASE__ : str = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_UpperCAmelCase ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_UpperCAmelCase, decimals=4 ), [ {"mask": {"hash": "115ad19f5f", "shape": (4_8_0, 6_4_0)}, "scores": 1.0444}, {"mask": {"hash": "6affa964c6", "shape": (4_8_0, 6_4_0)}, "scores": 1.021}, {"mask": {"hash": "dfe28a0388", "shape": (4_8_0, 6_4_0)}, "scores": 1.0167}, {"mask": {"hash": "c0a5f4a318", "shape": (4_8_0, 6_4_0)}, "scores": 1.0132}, {"mask": {"hash": "fe8065c197", "shape": (4_8_0, 6_4_0)}, "scores": 1.0053}, {"mask": {"hash": "e2d0b7a0b7", "shape": (4_8_0, 6_4_0)}, "scores": 0.9967}, {"mask": {"hash": "453c7844bd", "shape": (4_8_0, 6_4_0)}, "scores": 0.993}, {"mask": {"hash": "3d44f2926d", "shape": (4_8_0, 6_4_0)}, "scores": 0.9909}, {"mask": {"hash": "64033ddc3f", "shape": (4_8_0, 6_4_0)}, "scores": 0.9879}, {"mask": {"hash": "801064ff79", "shape": (4_8_0, 6_4_0)}, "scores": 0.9834}, {"mask": {"hash": "6172f276ef", "shape": (4_8_0, 6_4_0)}, "scores": 0.9716}, {"mask": {"hash": "b49e60e084", "shape": (4_8_0, 6_4_0)}, "scores": 0.9612}, {"mask": {"hash": "a811e775fd", "shape": (4_8_0, 6_4_0)}, "scores": 0.9599}, {"mask": {"hash": "a6a8ebcf4b", "shape": (4_8_0, 6_4_0)}, "scores": 0.9552}, {"mask": {"hash": "9d8257e080", "shape": (4_8_0, 6_4_0)}, "scores": 0.9532}, {"mask": {"hash": "32de6454a8", "shape": (4_8_0, 6_4_0)}, "scores": 0.9516}, {"mask": {"hash": "af3d4af2c8", "shape": (4_8_0, 6_4_0)}, "scores": 0.9499}, {"mask": {"hash": "3c6db475fb", "shape": (4_8_0, 6_4_0)}, "scores": 0.9483}, {"mask": {"hash": "c290813fb9", "shape": (4_8_0, 6_4_0)}, "scores": 0.9464}, {"mask": {"hash": "b6f0b8f606", "shape": (4_8_0, 6_4_0)}, "scores": 0.943}, {"mask": {"hash": "92ce16bfdf", "shape": (4_8_0, 6_4_0)}, "scores": 0.943}, {"mask": {"hash": "c749b25868", "shape": (4_8_0, 6_4_0)}, "scores": 0.9408}, {"mask": {"hash": "efb6cab859", "shape": (4_8_0, 6_4_0)}, "scores": 0.9335}, {"mask": {"hash": "1ff2eafb30", "shape": (4_8_0, 6_4_0)}, "scores": 0.9326}, {"mask": {"hash": "788b798e24", "shape": (4_8_0, 6_4_0)}, "scores": 0.9262}, {"mask": {"hash": "abea804f0e", "shape": (4_8_0, 6_4_0)}, "scores": 0.8999}, {"mask": {"hash": "7b9e8ddb73", "shape": (4_8_0, 6_4_0)}, "scores": 0.8986}, {"mask": {"hash": "cd24047c8a", "shape": (4_8_0, 6_4_0)}, "scores": 0.8984}, {"mask": {"hash": "6943e6bcbd", "shape": (4_8_0, 6_4_0)}, "scores": 0.8873}, {"mask": {"hash": "b5f47c9191", "shape": (4_8_0, 6_4_0)}, "scores": 0.8871} ], ) # fmt: on @require_torch @slow def A_ ( self : Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = "facebook/sam-vit-huge" SCREAMING_SNAKE_CASE__ : List[Any] = pipeline("mask-generation", model=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = image_segmenter( "http://images.cocodataset.org/val2017/000000039769.jpg", pred_iou_thresh=1, points_per_batch=2_5_6 ) # Shortening by hashing SCREAMING_SNAKE_CASE__ : List[str] = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_UpperCAmelCase ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_UpperCAmelCase, decimals=4 ), [ {"mask": {"hash": "115ad19f5f", "shape": (4_8_0, 6_4_0)}, "scores": 1.0444}, {"mask": {"hash": "6affa964c6", "shape": (4_8_0, 6_4_0)}, "scores": 1.0210}, {"mask": {"hash": "dfe28a0388", "shape": (4_8_0, 6_4_0)}, "scores": 1.0167}, {"mask": {"hash": "c0a5f4a318", "shape": (4_8_0, 6_4_0)}, "scores": 1.0132}, {"mask": {"hash": "fe8065c197", "shape": (4_8_0, 6_4_0)}, "scores": 1.0053}, ], )
663
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (DPMSolverSDEScheduler,) UpperCAmelCase_ = 10 def A_ ( self : List[str], **_UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "noise_sampler_seed": 0, } config.update(**_UpperCAmelCase ) return config def A_ ( self : Tuple ) -> int: """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_UpperCAmelCase ) def A_ ( self : int ) -> int: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001], [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_UpperCAmelCase, beta_end=_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : int = self.dummy_model() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Union[str, Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Dict = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config(prediction_type="v_prediction" ) SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Tuple = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def A_ ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : int = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Tuple = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Any = scheduler_class(**_UpperCAmelCase, use_karras_sigmas=_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : str = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
663
1
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = '''Hello world! cécé herlolip''' def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = FairseqRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) roberta.eval() # disable dropout SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.sentence_encoder SCREAMING_SNAKE_CASE__ : List[str] = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaXLForSequenceClassification(SCREAMING_SNAKE_CASE__ ) if classification_head else XLMRobertaXLForMaskedLM(SCREAMING_SNAKE_CASE__ ) model.eval() # Now let's copy all the weights. # Embeddings SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.embed_tokens.weight SCREAMING_SNAKE_CASE__ : str = roberta_sent_encoder.embed_positions.weight SCREAMING_SNAKE_CASE__ : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. SCREAMING_SNAKE_CASE__ : Any = roberta_sent_encoder.layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer SCREAMING_SNAKE_CASE__ : BertLayer = model.roberta.encoder.layer[i] SCREAMING_SNAKE_CASE__ : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] SCREAMING_SNAKE_CASE__ : RobertaAttention = layer.attention SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn_layer_norm.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn_layer_norm.bias # self attention SCREAMING_SNAKE_CASE__ : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = roberta_layer.self_attn.q_proj.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.self_attn.q_proj.bias SCREAMING_SNAKE_CASE__ : Any = roberta_layer.self_attn.k_proj.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn.k_proj.bias SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.self_attn.v_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.self_attn.v_proj.bias # self-attention output SCREAMING_SNAKE_CASE__ : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.weight SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.bias # this one is final layer norm SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.bias # intermediate SCREAMING_SNAKE_CASE__ : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.bias # output SCREAMING_SNAKE_CASE__ : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.fca.bias # end of layer if classification_head: SCREAMING_SNAKE_CASE__ : str = roberta.model.classification_heads["mnli"].dense.weight SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"].dense.bias SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head SCREAMING_SNAKE_CASE__ : Tuple = roberta.model.encoder.lm_head.dense.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.dense.bias SCREAMING_SNAKE_CASE__ : List[str] = roberta.model.encoder.lm_head.layer_norm.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta.model.encoder.lm_head.layer_norm.bias SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.encoder.lm_head.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. SCREAMING_SNAKE_CASE__ : torch.Tensor = roberta.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) # batch of size 1 SCREAMING_SNAKE_CASE__ : int = model(SCREAMING_SNAKE_CASE__ )[0] if classification_head: SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"](roberta.extract_features(SCREAMING_SNAKE_CASE__ ) ) else: SCREAMING_SNAKE_CASE__ : int = roberta.model(SCREAMING_SNAKE_CASE__ )[0] print(our_output.shape , their_output.shape ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(f'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 SCREAMING_SNAKE_CASE__ : int = torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(SCREAMING_SNAKE_CASE__ ).mkdir(parents=SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_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.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) _lowerCamelCase : Any = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
663
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = ["image_processor", "tokenizer"] UpperCAmelCase_ = "AutoImageProcessor" UpperCAmelCase_ = "AutoTokenizer" def __init__( self : Tuple, _UpperCAmelCase : str=None, _UpperCAmelCase : str=None, **_UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead.", _UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop("feature_extractor" ) SCREAMING_SNAKE_CASE__ : Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.image_processor SCREAMING_SNAKE_CASE__ : Any = False def __call__( self : List[str], *_UpperCAmelCase : Any, **_UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("images", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = args[0] SCREAMING_SNAKE_CASE__ : str = args[1:] if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: SCREAMING_SNAKE_CASE__ : Dict = self.image_processor(_UpperCAmelCase, *_UpperCAmelCase, **_UpperCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if text is None: return inputs elif images is None: return encodings else: SCREAMING_SNAKE_CASE__ : Optional[int] = encodings["input_ids"] return inputs def A_ ( self : Dict, *_UpperCAmelCase : Tuple, **_UpperCAmelCase : Dict ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : List[str], *_UpperCAmelCase : int, **_UpperCAmelCase : Dict ) -> Any: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) @contextmanager def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your images inputs, or in a separate call." ) SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False def A_ ( self : Tuple, _UpperCAmelCase : List[Any], _UpperCAmelCase : int=False, _UpperCAmelCase : Optional[Any]=None ) -> Any: """simple docstring""" if added_vocab is None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer.get_added_vocab() SCREAMING_SNAKE_CASE__ : str = {} while tokens: SCREAMING_SNAKE_CASE__ : Dict = re.search(r"<s_(.*?)>", _UpperCAmelCase, re.IGNORECASE ) if start_token is None: break SCREAMING_SNAKE_CASE__ : Any = start_token.group(1 ) SCREAMING_SNAKE_CASE__ : Dict = re.search(rF'''</s_{key}>''', _UpperCAmelCase, re.IGNORECASE ) SCREAMING_SNAKE_CASE__ : Any = start_token.group() if end_token is None: SCREAMING_SNAKE_CASE__ : List[str] = tokens.replace(_UpperCAmelCase, "" ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = end_token.group() SCREAMING_SNAKE_CASE__ : List[str] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}''', _UpperCAmelCase, re.IGNORECASE ) if content is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node SCREAMING_SNAKE_CASE__ : str = self.tokenajson(_UpperCAmelCase, is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if value: if len(_UpperCAmelCase ) == 1: SCREAMING_SNAKE_CASE__ : str = value[0] SCREAMING_SNAKE_CASE__ : List[str] = value else: # leaf nodes SCREAMING_SNAKE_CASE__ : Optional[int] = [] for leaf in content.split(r"<sep/>" ): SCREAMING_SNAKE_CASE__ : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": SCREAMING_SNAKE_CASE__ : str = leaf[1:-2] # for categorical special tokens output[key].append(_UpperCAmelCase ) if len(output[key] ) == 1: SCREAMING_SNAKE_CASE__ : str = output[key][0] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokens[tokens.find(_UpperCAmelCase ) + len(_UpperCAmelCase ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if len(_UpperCAmelCase ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def A_ ( self : str ) -> Optional[Any]: """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.", _UpperCAmelCase, ) return self.image_processor_class @property def A_ ( self : int ) -> List[str]: """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.", _UpperCAmelCase, ) return self.image_processor
663
1
from __future__ import annotations def _a ( SCREAMING_SNAKE_CASE__ : int ) -> list[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [True] * limit SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : List[Any] = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): SCREAMING_SNAKE_CASE__ : Tuple = i * 2 while index < limit: SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = index + i SCREAMING_SNAKE_CASE__ : Tuple = [2] for i in range(3 , SCREAMING_SNAKE_CASE__ , 2 ): if is_prime[i]: primes.append(SCREAMING_SNAKE_CASE__ ) return primes def _a ( SCREAMING_SNAKE_CASE__ : int = 1_00_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = prime_sieve(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): for j in range(i + length , len(SCREAMING_SNAKE_CASE__ ) ): SCREAMING_SNAKE_CASE__ : Optional[Any] = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: SCREAMING_SNAKE_CASE__ : List[str] = j - i SCREAMING_SNAKE_CASE__ : Tuple = sol return largest if __name__ == "__main__": print(f"{solution() = }")
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _lowerCamelCase : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = ['''BartphoTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : int = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "sew-d" def __init__( self : str, _UpperCAmelCase : str=3_2, _UpperCAmelCase : Optional[int]=7_6_8, _UpperCAmelCase : Optional[int]=1_2, _UpperCAmelCase : Tuple=1_2, _UpperCAmelCase : str=3_0_7_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Optional[Any]=5_1_2, _UpperCAmelCase : int=2_5_6, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Dict=True, _UpperCAmelCase : int=("p2c", "c2p"), _UpperCAmelCase : Dict="layer_norm", _UpperCAmelCase : Tuple="gelu_python", _UpperCAmelCase : List[Any]=0.1, _UpperCAmelCase : Optional[int]=0.1, _UpperCAmelCase : int=0.1, _UpperCAmelCase : str=0.0, _UpperCAmelCase : int=0.1, _UpperCAmelCase : List[str]=0.02, _UpperCAmelCase : int=1E-7, _UpperCAmelCase : Union[str, Any]=1E-5, _UpperCAmelCase : Any="group", _UpperCAmelCase : List[str]="gelu", _UpperCAmelCase : Any=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2), _UpperCAmelCase : List[str]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1), _UpperCAmelCase : List[str]=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1), _UpperCAmelCase : Any=False, _UpperCAmelCase : Any=1_2_8, _UpperCAmelCase : List[str]=1_6, _UpperCAmelCase : str=True, _UpperCAmelCase : Dict=0.05, _UpperCAmelCase : Any=1_0, _UpperCAmelCase : Dict=2, _UpperCAmelCase : str=0.0, _UpperCAmelCase : Dict=1_0, _UpperCAmelCase : Union[str, Any]=0, _UpperCAmelCase : Optional[Any]="mean", _UpperCAmelCase : str=False, _UpperCAmelCase : Dict=False, _UpperCAmelCase : int=2_5_6, _UpperCAmelCase : List[Any]=0, _UpperCAmelCase : Any=1, _UpperCAmelCase : Optional[Any]=2, **_UpperCAmelCase : Tuple, ) -> Any: """simple docstring""" super().__init__(**_UpperCAmelCase, pad_token_id=_UpperCAmelCase, bos_token_id=_UpperCAmelCase, eos_token_id=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : int = feat_extract_norm SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract_activation SCREAMING_SNAKE_CASE__ : Any = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = conv_bias SCREAMING_SNAKE_CASE__ : List[Any] = num_conv_pos_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE__ : Optional[int] = len(self.conv_dim ) SCREAMING_SNAKE_CASE__ : str = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = squeeze_factor SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = position_buckets SCREAMING_SNAKE_CASE__ : Optional[Any] = share_att_key SCREAMING_SNAKE_CASE__ : List[Any] = relative_attention SCREAMING_SNAKE_CASE__ : int = norm_rel_ebd SCREAMING_SNAKE_CASE__ : int = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = hidden_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = activation_dropout SCREAMING_SNAKE_CASE__ : Dict = feat_proj_dropout SCREAMING_SNAKE_CASE__ : List[Any] = final_dropout SCREAMING_SNAKE_CASE__ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_layer_norm_eps SCREAMING_SNAKE_CASE__ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE__ : Any = 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 SCREAMING_SNAKE_CASE__ : str = apply_spec_augment SCREAMING_SNAKE_CASE__ : List[str] = mask_time_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = mask_time_length SCREAMING_SNAKE_CASE__ : Optional[int] = mask_time_min_masks SCREAMING_SNAKE_CASE__ : Optional[Any] = mask_feature_prob SCREAMING_SNAKE_CASE__ : str = mask_feature_length SCREAMING_SNAKE_CASE__ : Optional[int] = mask_feature_min_masks # ctc loss SCREAMING_SNAKE_CASE__ : Optional[Any] = ctc_loss_reduction SCREAMING_SNAKE_CASE__ : List[str] = ctc_zero_infinity # sequence classification SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_weighted_layer_sum SCREAMING_SNAKE_CASE__ : Optional[int] = classifier_proj_size @property def A_ ( self : Optional[Any] ) -> int: """simple docstring""" return functools.reduce(operator.mul, self.conv_stride, 1 )
663
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class lowerCamelCase : """simple docstring""" def __init__( self : Any, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Union[str, Any]=1_3, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : str=1_6, _UpperCAmelCase : Tuple=[1, 2, 1], _UpperCAmelCase : List[str]=[2, 2, 4], _UpperCAmelCase : Tuple=2, _UpperCAmelCase : str=2.0, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=0.0, _UpperCAmelCase : Any=0.0, _UpperCAmelCase : Optional[int]=0.1, _UpperCAmelCase : int="gelu", _UpperCAmelCase : Any=False, _UpperCAmelCase : Any=True, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Any=1E-5, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : List[Any]=None, _UpperCAmelCase : str=True, _UpperCAmelCase : Union[str, Any]=1_0, _UpperCAmelCase : List[str]=8, _UpperCAmelCase : Union[str, Any]=["stage1", "stage2", "stage3"], _UpperCAmelCase : Any=[1, 2, 3], ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = embed_dim SCREAMING_SNAKE_CASE__ : List[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = num_heads SCREAMING_SNAKE_CASE__ : str = window_size SCREAMING_SNAKE_CASE__ : Any = mlp_ratio SCREAMING_SNAKE_CASE__ : List[str] = qkv_bias SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = drop_path_rate SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Tuple = patch_norm SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : Optional[int] = use_labels SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_stride SCREAMING_SNAKE_CASE__ : List[Any] = out_features SCREAMING_SNAKE_CASE__ : Dict = out_indices def A_ ( self : List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[int] ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, out_features=self.out_features, out_indices=self.out_indices, ) def A_ ( self : Dict, _UpperCAmelCase : int, _UpperCAmelCase : str, _UpperCAmelCase : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def A_ ( self : Optional[int], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any, _UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = MaskFormerSwinBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ), len(config.out_features ) ) self.parent.assertListEqual(model.channels, [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = ["stem"] SCREAMING_SNAKE_CASE__ : str = MaskFormerSwinBackbone(config=_UpperCAmelCase ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) UpperCAmelCase_ = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = MaskFormerSwinModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = ConfigTester(self, config_class=_UpperCAmelCase, embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def A_ ( self : Any ) -> List[Any]: """simple docstring""" pass def A_ ( self : Tuple ) -> Any: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A_ ( self : int ) -> Optional[Any]: """simple docstring""" return def A_ ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_UpperCAmelCase ) @unittest.skip("Swin does not use inputs_embeds" ) def A_ ( self : Any ) -> Optional[int]: """simple docstring""" pass @unittest.skip("Swin does not support feedforward chunking" ) def A_ ( self : List[str] ) -> Optional[int]: """simple docstring""" pass def A_ ( self : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, nn.Linear ) ) def A_ ( self : Union[str, Any] ) -> List[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__ : Dict = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def A_ ( self : Dict ) -> List[str]: """simple docstring""" pass def A_ ( self : List[str], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr( self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_UpperCAmelCase ), _UpperCAmelCase ) # Swin has a different seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Dict = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Any = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def A_ ( self : List[Any] ) -> Dict: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Dict ) -> str: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" pass def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_UpperCAmelCase : Optional[Any] ): SCREAMING_SNAKE_CASE__ : Dict = 0 return t def check_equivalence(_UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : Optional[Any]={} ): with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ).to_tuple() def recursive_check(_UpperCAmelCase : int, _UpperCAmelCase : Dict ): if isinstance(_UpperCAmelCase, (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_UpperCAmelCase, _UpperCAmelCase ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif isinstance(_UpperCAmelCase, _UpperCAmelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values(), dict_object.values() ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_UpperCAmelCase ), set_nan_tensor_to_zero(_UpperCAmelCase ), atol=1E-5 ), msg=( "Tuple and dict output are not equal. Difference:" F''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' F''' {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}. Dict has''' F''' `nan`: {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}.''' ), ) recursive_check(_UpperCAmelCase, _UpperCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) @require_torch class lowerCamelCase (unittest.TestCase , __lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (MaskFormerSwinBackbone,) if is_torch_available() else () UpperCAmelCase_ = MaskFormerSwinConfig def A_ ( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModelTester(self ) def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = backbone_class(_UpperCAmelCase ) backbone.to(_UpperCAmelCase ) backbone.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps, _UpperCAmelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels ): self.assertTrue(feature_map.shape[:2], (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase, output_hidden_states=_UpperCAmelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ), len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:], backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels), (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: SCREAMING_SNAKE_CASE__ : int = backbone(**_UpperCAmelCase, output_attentions=_UpperCAmelCase ) self.assertIsNotNone(outputs.attentions )
663
1
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers _lowerCamelCase : Tuple = float('''nan''') class lowerCamelCase : """simple docstring""" def __init__( self : int, _UpperCAmelCase : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = sys.stdout SCREAMING_SNAKE_CASE__ : Dict = open(_UpperCAmelCase, "a" ) def __getattr__( self : Dict, _UpperCAmelCase : List[str] ) -> List[str]: """simple docstring""" return getattr(self.stdout, _UpperCAmelCase ) def A_ ( self : List[Any], _UpperCAmelCase : Any ) -> Optional[int]: """simple docstring""" self.stdout.write(_UpperCAmelCase ) # strip tqdm codes self.file.write(re.sub(r"^.*\r", "", _UpperCAmelCase, 0, re.M ) ) def _a ( SCREAMING_SNAKE_CASE__ : List[str]=80 , SCREAMING_SNAKE_CASE__ : Any=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # deal with critical env vars SCREAMING_SNAKE_CASE__ : Any = ["CUDA_VISIBLE_DEVICES"] for key in env_keys: SCREAMING_SNAKE_CASE__ : Tuple = os.environ.get(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if val is not None: cmd.append(f'''{key}={val}''' ) # python executable (not always needed if the script is executable) SCREAMING_SNAKE_CASE__ : Tuple = sys.executable if full_python_path else sys.executable.split("/" )[-1] cmd.append(SCREAMING_SNAKE_CASE__ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : int = "" while len(SCREAMING_SNAKE_CASE__ ) > 0: current_line += f'''{cmd.pop(0 )} ''' if len(SCREAMING_SNAKE_CASE__ ) == 0 or len(SCREAMING_SNAKE_CASE__ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[str] = "" return "\\\n".join(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = re.sub(R"[\\\n]+" , " " , args.base_cmd ) # remove --output_dir if any and set our own SCREAMING_SNAKE_CASE__ : int = re.sub("--output_dir\s+[^\s]+" , "" , args.base_cmd ) args.base_cmd += f''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir SCREAMING_SNAKE_CASE__ : Optional[Any] = re.sub("--overwrite_output_dir\s+" , "" , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 1_00 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 1_0.3_1, 1_0_0.2, 5_5.6_6_6_6, 2_2_2.2_2_2_2_2_2_2_2] )} , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = subprocess.run(SCREAMING_SNAKE_CASE__ , capture_output=SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) if verbose: print("STDOUT" , result.stdout ) print("STDERR" , result.stderr ) # save the streams SCREAMING_SNAKE_CASE__ : str = variation.replace(" " , "-" ) with open(Path(SCREAMING_SNAKE_CASE__ ) / f'''log.{prefix}.stdout.txt''' , "w" ) as f: f.write(result.stdout ) with open(Path(SCREAMING_SNAKE_CASE__ ) / f'''log.{prefix}.stderr.txt''' , "w" ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print("failed" ) return {target_metric_key: nan} with io.open(f'''{output_dir}/all_results.json''' , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = json.load(SCREAMING_SNAKE_CASE__ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _a ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = f'''{id}: {variation:<{longest_variation_len}}''' SCREAMING_SNAKE_CASE__ : List[str] = f'''{preamble}: ''' SCREAMING_SNAKE_CASE__ : Optional[Any] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(SCREAMING_SNAKE_CASE__ ) , desc=SCREAMING_SNAKE_CASE__ , leave=SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Any = process_run_single( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = single_run_metrics[target_metric_key] if not math.isnan(SCREAMING_SNAKE_CASE__ ): metrics.append(SCREAMING_SNAKE_CASE__ ) results.append(SCREAMING_SNAKE_CASE__ ) outcome += "✓" else: outcome += "✘" SCREAMING_SNAKE_CASE__ : int = f'''\33[2K\r{outcome}''' if len(SCREAMING_SNAKE_CASE__ ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} SCREAMING_SNAKE_CASE__ : List[Any] = round(mean_metrics[target_metric_key] , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = f'''{outcome} {mean_target}''' if len(SCREAMING_SNAKE_CASE__ ) > 1: results_str += f''' {tuple(round(SCREAMING_SNAKE_CASE__ , 2 ) for x in results )}''' print(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = variation return mean_metrics else: print(SCREAMING_SNAKE_CASE__ ) return {variation_key: variation, target_metric_key: nan} def _a ( ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = torch.cuda.get_device_properties(torch.device("cuda" ) ) return f''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def _a ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = pd.DataFrame(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "variation" SCREAMING_SNAKE_CASE__ : List[str] = "diff_%" SCREAMING_SNAKE_CASE__ : Union[str, Any] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan SCREAMING_SNAKE_CASE__ : int = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(SCREAMING_SNAKE_CASE__ ): # as a fallback, use the minimal value as the sentinel SCREAMING_SNAKE_CASE__ : List[Any] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = df.apply( lambda SCREAMING_SNAKE_CASE__ : round(1_00 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis="columns" , ) # re-order columns SCREAMING_SNAKE_CASE__ : int = [variation_key, target_metric_key, diff_key, *report_metric_keys] SCREAMING_SNAKE_CASE__ : Optional[Any] = df.reindex(SCREAMING_SNAKE_CASE__ , axis="columns" ) # reorder cols # capitalize SCREAMING_SNAKE_CASE__ : List[Any] = df.rename(str.capitalize , axis="columns" ) # make the cols as narrow as possible SCREAMING_SNAKE_CASE__ : Dict = df.rename(lambda SCREAMING_SNAKE_CASE__ : c.replace("_" , "<br>" ) , axis="columns" ) SCREAMING_SNAKE_CASE__ : Optional[int] = df.rename(lambda SCREAMING_SNAKE_CASE__ : c.replace("_" , "\n" ) , axis="columns" ) SCREAMING_SNAKE_CASE__ : str = ["", "Copy between the cut-here-lines and paste as is to github or a forum"] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=SCREAMING_SNAKE_CASE__ , floatfmt=".2f" )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=SCREAMING_SNAKE_CASE__ , floatfmt=".2f" )] print("\n\n".join(SCREAMING_SNAKE_CASE__ ) ) def _a ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument( "--base-cmd" , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help="Base cmd" , ) parser.add_argument( "--variations" , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , nargs="+" , required=SCREAMING_SNAKE_CASE__ , help="Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'" , ) parser.add_argument( "--base-variation" , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , help="Baseline variation to compare to. if None the minimal target value will be used to compare against" , ) parser.add_argument( "--target-metric-key" , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second" , ) parser.add_argument( "--report-metric-keys" , default="" , type=SCREAMING_SNAKE_CASE__ , help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples" , ) parser.add_argument( "--repeat-times" , default=1 , type=SCREAMING_SNAKE_CASE__ , help="How many times to re-run each variation - an average will be reported" , ) parser.add_argument( "--output_dir" , default="output_benchmark" , type=SCREAMING_SNAKE_CASE__ , help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked" , ) parser.add_argument( "--verbose" , default=SCREAMING_SNAKE_CASE__ , action="store_true" , help="Whether to show the outputs of each run or just the benchmark progress" , ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Optional[Any] = args.output_dir Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_base_command(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # split each dimension into its --foo variations SCREAMING_SNAKE_CASE__ : int = [list(map(str.strip , re.split(R"\|" , SCREAMING_SNAKE_CASE__ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(map(str.strip , map(" ".join , itertools.product(*SCREAMING_SNAKE_CASE__ ) ) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = max(len(SCREAMING_SNAKE_CASE__ ) for x in variations ) # split wanted keys SCREAMING_SNAKE_CASE__ : Optional[Any] = args.report_metric_keys.split() # capture prints into a log file for convenience SCREAMING_SNAKE_CASE__ : str = f'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(f'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(f'''and this script\'s output is also piped into {report_fn}''' ) SCREAMING_SNAKE_CASE__ : Any = Tee(SCREAMING_SNAKE_CASE__ ) print(f'''\n*** Running {len(SCREAMING_SNAKE_CASE__ )} benchmarks:''' ) print(f'''Base command: {" ".join(SCREAMING_SNAKE_CASE__ )}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "variation" SCREAMING_SNAKE_CASE__ : Optional[int] = [] for id, variation in enumerate(tqdm(SCREAMING_SNAKE_CASE__ , desc="Total completion: " , leave=SCREAMING_SNAKE_CASE__ ) ): SCREAMING_SNAKE_CASE__ : Tuple = base_cmd + variation.split() results.append( process_run( id + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , args.target_metric_key , SCREAMING_SNAKE_CASE__ , args.repeat_times , SCREAMING_SNAKE_CASE__ , args.verbose , ) ) process_results(SCREAMING_SNAKE_CASE__ , args.target_metric_key , SCREAMING_SNAKE_CASE__ , args.base_variation , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
663
from ....configuration_utils import PretrainedConfig from ....utils import logging _lowerCamelCase : Any = logging.get_logger(__name__) # TODO: upload to AWS _lowerCamelCase : str = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json''' ), } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "retribert" def __init__( self : Optional[Any], _UpperCAmelCase : Dict=3_0_5_2_2, _UpperCAmelCase : List[str]=7_6_8, _UpperCAmelCase : Tuple=8, _UpperCAmelCase : Optional[Any]=1_2, _UpperCAmelCase : Union[str, Any]=3_0_7_2, _UpperCAmelCase : Dict="gelu", _UpperCAmelCase : Tuple=0.1, _UpperCAmelCase : str=0.1, _UpperCAmelCase : List[str]=5_1_2, _UpperCAmelCase : Optional[int]=2, _UpperCAmelCase : Dict=0.02, _UpperCAmelCase : Any=1E-12, _UpperCAmelCase : Dict=True, _UpperCAmelCase : Any=1_2_8, _UpperCAmelCase : int=0, **_UpperCAmelCase : List[str], ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = share_encoders SCREAMING_SNAKE_CASE__ : int = projection_dim
663
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase : Optional[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = ['''MobileViTFeatureExtractor'''] _lowerCamelCase : List[str] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[Any] = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin _lowerCamelCase : int = False @skip_mps class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = StableDiffusionAttendAndExcitePipeline UpperCAmelCase_ = False UpperCAmelCase_ = TEXT_TO_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"} ) UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def A_ ( cls : str ) -> Union[str, Any]: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : Tuple ) -> str: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : Any ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4), layers_per_block=1, sample_size=3_2, in_channels=4, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=3_2, attention_head_dim=(2, 4), use_linear_projection=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=_UpperCAmelCase, set_alpha_to_one=_UpperCAmelCase, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = AutoencoderKL( block_out_channels=[3_2, 6_4], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, sample_size=1_2_8, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=3_2, intermediate_size=3_7, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, hidden_act="gelu", projection_dim=5_1_2, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTextModel(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def A_ ( self : Optional[Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Any=0 ) -> Optional[Any]: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : Tuple = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = { "prompt": "a cat and a frog", "token_indices": [2, 5], "generator": generator, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", "max_iter_to_alter": 2, "thresholds": {0: 0.7}, } return inputs def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = "cpu" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.pipeline_class(**_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_dummy_inputs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = pipe(**_UpperCAmelCase ).images SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 6_4, 6_4, 3) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) SCREAMING_SNAKE_CASE__ : Dict = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_UpperCAmelCase, 1E-3 ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def A_ ( self : Any ) -> str: """simple docstring""" # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : Optional[Any] ) -> str: """simple docstring""" self._test_inference_batch_single_identical(batch_size=2, expected_max_diff=7E-4 ) def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def A_ ( self : Any ) -> List[str]: """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" super().test_save_load_local(expected_max_difference=5E-4 ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class lowerCamelCase (unittest.TestCase ): """simple docstring""" @classmethod def A_ ( cls : Union[str, Any] ) -> Tuple: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : List[str] ) -> List[str]: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(5_1 ) SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionAttendAndExcitePipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=_UpperCAmelCase, torch_dtype=torch.floataa ) pipe.to("cuda" ) SCREAMING_SNAKE_CASE__ : List[str] = "a painting of an elephant with glasses" SCREAMING_SNAKE_CASE__ : Optional[int] = [5, 7] SCREAMING_SNAKE_CASE__ : str = pipe( prompt=_UpperCAmelCase, token_indices=_UpperCAmelCase, guidance_scale=7.5, generator=_UpperCAmelCase, num_inference_steps=5, max_iter_to_alter=5, output_type="numpy", ).images[0] SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy" ) assert np.abs((expected_image - image).max() ) < 5E-1
663
1
import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel class lowerCamelCase : """simple docstring""" def __init__( self : Optional[int], _UpperCAmelCase : List[str], _UpperCAmelCase : List[str]=1_3, _UpperCAmelCase : Any=7, _UpperCAmelCase : Any=True, _UpperCAmelCase : int=True, _UpperCAmelCase : Optional[Any]=True, _UpperCAmelCase : Union[str, Any]=True, _UpperCAmelCase : List[Any]=9_9, _UpperCAmelCase : str=3_2, _UpperCAmelCase : str=5, _UpperCAmelCase : List[str]=4, _UpperCAmelCase : Dict=4, _UpperCAmelCase : List[str]="gelu", _UpperCAmelCase : Any=0.0, _UpperCAmelCase : Tuple=0.1, _UpperCAmelCase : str=True, _UpperCAmelCase : List[Any]=5_1_2, _UpperCAmelCase : int=1_6, _UpperCAmelCase : Tuple=2, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : int=4, _UpperCAmelCase : Any=None, ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = parent SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE__ : List[str] = seq_length SCREAMING_SNAKE_CASE__ : List[Any] = is_training SCREAMING_SNAKE_CASE__ : Dict = use_input_mask SCREAMING_SNAKE_CASE__ : Any = use_token_type_ids SCREAMING_SNAKE_CASE__ : List[str] = use_labels SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_multiple_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : Any = hidden_dropout SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = weight_tying SCREAMING_SNAKE_CASE__ : Any = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : str = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Dict = scope def A_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : int = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() return config, input_ids, input_mask, token_labels def A_ ( self : int ) -> Optional[int]: """simple docstring""" return GPTNeoXJapaneseConfig( 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_multiple_size=self.intermediate_multiple_size, hidden_act=self.hidden_act, hidden_dropout=self.hidden_dropout, attention_dropout=self.attention_dropout, weight_tying=self.weight_tying, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=_UpperCAmelCase, initializer_range=self.initializer_range, ) def A_ ( self : str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : int = True return config, input_ids, input_mask, token_labels def A_ ( self : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[int], _UpperCAmelCase : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTNeoXJapaneseModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def A_ ( self : str, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any, _UpperCAmelCase : List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : List[str] = GPTNeoXJapaneseModel(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def A_ ( self : List[Any], _UpperCAmelCase : Dict, _UpperCAmelCase : Any, _UpperCAmelCase : Optional[int], _UpperCAmelCase : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = GPTNeoXJapaneseForCausalLM(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def A_ ( self : List[str], _UpperCAmelCase : str, _UpperCAmelCase : List[Any], _UpperCAmelCase : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : Tuple = GPTNeoXJapaneseForCausalLM(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() # first forward pass SCREAMING_SNAKE_CASE__ : List[str] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3), vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Any = torch.cat([input_ids, next_tokens], dim=-1 ) SCREAMING_SNAKE_CASE__ : int = torch.cat([input_mask, next_mask], dim=-1 ) SCREAMING_SNAKE_CASE__ : Any = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, output_hidden_states=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_no_past["hidden_states"][0] SCREAMING_SNAKE_CASE__ : Any = model( _UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase, output_hidden_states=_UpperCAmelCase, )["hidden_states"][0] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,), output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_UpperCAmelCase, _UpperCAmelCase, atol=1E-3 ) ) def A_ ( self : Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () UpperCAmelCase_ = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else () UpperCAmelCase_ = ( {"feature-extraction": GPTNeoXJapaneseModel, "text-generation": GPTNeoXJapaneseForCausalLM} if is_torch_available() else {} ) UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = GPTNeoXJapaneseModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self, config_class=_UpperCAmelCase, hidden_size=3_7 ) def A_ ( self : int ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : int ) -> List[str]: """simple docstring""" # This regression test was failing with PyTorch < 1.3 SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_decoder() SCREAMING_SNAKE_CASE__ : Optional[Any] = None self.model_tester.create_and_check_model_as_decoder(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*_UpperCAmelCase ) @slow def A_ ( self : Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = "abeja/gpt-neox-japanese-2.7b" SCREAMING_SNAKE_CASE__ : Tuple = ["データサイエンティストとは、", "100年後に必要とされる会社は、", "フルリモートの環境で働くために必要なことは、", "国境の長いトンネルを抜けると", "美味しい日本食といえば、"] SCREAMING_SNAKE_CASE__ : Dict = [ "データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。", "100年後に必要とされる会社は、「人」が中心の会社です。", "フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。", "国境の長いトンネルを抜けると、そこは雪国だった。", "美味しい日本食といえば、やっぱりお寿司ですよね。", ] SCREAMING_SNAKE_CASE__ : List[str] = GPTNeoXJapaneseTokenizer.from_pretrained(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = GPTNeoXJapaneseForCausalLM.from_pretrained(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = [] for prompt in prompts: SCREAMING_SNAKE_CASE__ : str = tokenizer(_UpperCAmelCase, return_tensors="pt" ).input_ids SCREAMING_SNAKE_CASE__ : int = model.generate(_UpperCAmelCase, max_length=5_0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode(_UpperCAmelCase, skip_special_tokens=_UpperCAmelCase ) predicted_outputs += generated_string self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase )
663
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = PegasusConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=False, _UpperCAmelCase : Union[str, Any]=9_9, _UpperCAmelCase : Optional[Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=4, _UpperCAmelCase : str=3_7, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=4_0, _UpperCAmelCase : Any=2, _UpperCAmelCase : int=1, _UpperCAmelCase : str=0, ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : str = eos_token_id SCREAMING_SNAKE_CASE__ : Dict = pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = bos_token_id def A_ ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_pegasus_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Union[str, Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFPegasusModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : str = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : int = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : int = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : str = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Optional[Any] = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : List[str]=None , ) -> Any: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase_ = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFPegasusModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_sentencepiece @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] UpperCAmelCase_ = [ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to" " reduce the risk of wildfires.", "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.", ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase_ = "google/pegasus-xsum" @cached_property def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def A_ ( self : str, **_UpperCAmelCase : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.translate_src_text(**_UpperCAmelCase ) assert self.expected_text == generated_words def A_ ( self : Any, **_UpperCAmelCase : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, **_UpperCAmelCase, padding=_UpperCAmelCase, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : List[str] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase ) return generated_words @slow def A_ ( self : List[Any] ) -> Any: """simple docstring""" self._assert_generated_batch_equal_expected()
663
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCamelCase : List[str] = logging.getLogger(__name__) @dataclass class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase_ = field( default=__lowerCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase_ = field( default=__lowerCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase_ = field( default=__lowerCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) UpperCAmelCase_ = field(default=__lowerCamelCase , metadata={"help": "Whether tp freeze the encoder."} ) UpperCAmelCase_ = field(default=__lowerCamelCase , metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase_ = field( default="summarization" , metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"} , ) UpperCAmelCase_ = field( default=1024 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCAmelCase_ = field( default=128 , metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCAmelCase_ = field( default=142 , metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) } , ) UpperCAmelCase_ = field( default=142 , metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCAmelCase_ = field(default=-1 , metadata={"help": "# training examples. -1 means use all."} ) UpperCAmelCase_ = field(default=-1 , metadata={"help": "# validation examples. -1 means use all."} ) UpperCAmelCase_ = field(default=-1 , metadata={"help": "# test examples. -1 means use all."} ) UpperCAmelCase_ = field(default=__lowerCamelCase , metadata={"help": "Source language id for translation."} ) UpperCAmelCase_ = field(default=__lowerCamelCase , metadata={"help": "Target language id for translation."} ) UpperCAmelCase_ = field(default=__lowerCamelCase , metadata={"help": "# num_beams to use for evaluation."} ) UpperCAmelCase_ = field( default=__lowerCamelCase , metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."} , ) def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: '''simple docstring''' logger.info(f'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(f''' {key} = {metrics[key]}''' ) save_json(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , f'''{split}_results.json''' ) ) def _a ( ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args_into_dataclasses() check_output_dir(SCREAMING_SNAKE_CASE__ ) # 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.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # 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() logger.info("Training/evaluation parameters %s" , SCREAMING_SNAKE_CASE__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) SCREAMING_SNAKE_CASE__ : List[Any] = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ), f'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : int = 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 , ) SCREAMING_SNAKE_CASE__ : Dict = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=SCREAMING_SNAKE_CASE__ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(SCREAMING_SNAKE_CASE__ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: SCREAMING_SNAKE_CASE__ : str = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(SCREAMING_SNAKE_CASE__ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.lang_code_to_id[data_args.tgt_lang] else: SCREAMING_SNAKE_CASE__ : Dict = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(SCREAMING_SNAKE_CASE__ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) SCREAMING_SNAKE_CASE__ : Optional[int] = SeqaSeqDataset # Get datasets SCREAMING_SNAKE_CASE__ : Optional[Any] = ( dataset_class( SCREAMING_SNAKE_CASE__ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE__ : List[Any] = ( dataset_class( SCREAMING_SNAKE_CASE__ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) SCREAMING_SNAKE_CASE__ : Any = ( dataset_class( SCREAMING_SNAKE_CASE__ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Tuple = ( build_compute_metrics_fn(data_args.task , SCREAMING_SNAKE_CASE__ ) if training_args.predict_with_generate else None ) SCREAMING_SNAKE_CASE__ : Dict = SeqaSeqTrainer( model=SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , data_args=SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , data_collator=SeqaSeqDataCollator( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : Dict = {} # Training if training_args.do_train: logger.info("*** Train ***" ) SCREAMING_SNAKE_CASE__ : int = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) SCREAMING_SNAKE_CASE__ : Optional[Any] = train_result.metrics SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , SCREAMING_SNAKE_CASE__ , training_args.output_dir ) all_metrics.update(SCREAMING_SNAKE_CASE__ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) SCREAMING_SNAKE_CASE__ : Optional[int] = trainer.evaluate(metric_key_prefix="val" ) SCREAMING_SNAKE_CASE__ : Any = data_args.n_val SCREAMING_SNAKE_CASE__ : Tuple = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , SCREAMING_SNAKE_CASE__ , training_args.output_dir ) all_metrics.update(SCREAMING_SNAKE_CASE__ ) if training_args.do_predict: logger.info("*** Predict ***" ) SCREAMING_SNAKE_CASE__ : int = trainer.predict(test_dataset=SCREAMING_SNAKE_CASE__ , metric_key_prefix="test" ) SCREAMING_SNAKE_CASE__ : Optional[int] = test_output.metrics SCREAMING_SNAKE_CASE__ : Optional[Any] = data_args.n_test if trainer.is_world_process_zero(): SCREAMING_SNAKE_CASE__ : List[Any] = round(metrics["test_loss"] , 4 ) handle_metrics("test" , SCREAMING_SNAKE_CASE__ , training_args.output_dir ) all_metrics.update(SCREAMING_SNAKE_CASE__ ) if training_args.predict_with_generate: SCREAMING_SNAKE_CASE__ : int = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = lmap(str.strip , SCREAMING_SNAKE_CASE__ ) write_txt_file(SCREAMING_SNAKE_CASE__ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(SCREAMING_SNAKE_CASE__ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def _a ( SCREAMING_SNAKE_CASE__ : Any ) -> List[str]: '''simple docstring''' main() if __name__ == "__main__": main()
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase : List[str] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : int = {'''vocab_file''': '''sentencepiece.bpe.model'''} _lowerCamelCase : List[Any] = { '''vocab_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model''' ), }, } _lowerCamelCase : List[Any] = { '''moussaKam/mbarthez''': 1_0_2_4, '''moussaKam/barthez''': 1_0_2_4, '''moussaKam/barthez-orangesum-title''': 1_0_2_4, } _lowerCamelCase : Optional[int] = '''▁''' class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = ["input_ids", "attention_mask"] def __init__( self : int, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any="<s>", _UpperCAmelCase : Dict="</s>", _UpperCAmelCase : Any="</s>", _UpperCAmelCase : Optional[int]="<s>", _UpperCAmelCase : Union[str, Any]="<unk>", _UpperCAmelCase : Dict="<pad>", _UpperCAmelCase : List[str]="<mask>", _UpperCAmelCase : Optional[Dict[str, Any]] = None, **_UpperCAmelCase : Optional[int], ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : str = AddedToken(_UpperCAmelCase, lstrip=_UpperCAmelCase, rstrip=_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ) else mask_token SCREAMING_SNAKE_CASE__ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCAmelCase, eos_token=_UpperCAmelCase, unk_token=_UpperCAmelCase, sep_token=_UpperCAmelCase, cls_token=_UpperCAmelCase, pad_token=_UpperCAmelCase, mask_token=_UpperCAmelCase, sp_model_kwargs=self.sp_model_kwargs, **_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : str = vocab_file SCREAMING_SNAKE_CASE__ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Any = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} SCREAMING_SNAKE_CASE__ : str = len(self.sp_model ) - 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def A_ ( self : Tuple, _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : str, _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None, _UpperCAmelCase : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase, token_ids_a=_UpperCAmelCase, already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1, 1] + ([0] * len(_UpperCAmelCase )) + [1] def A_ ( self : List[Any], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A_ ( self : Optional[int] ) -> int: """simple docstring""" return len(self.sp_model ) def A_ ( self : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = {self.convert_ids_to_tokens(_UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : Optional[int], _UpperCAmelCase : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_UpperCAmelCase, out_type=_UpperCAmelCase ) def A_ ( self : Union[str, Any], _UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.sp_model.PieceToId(_UpperCAmelCase ) return spm_id if spm_id else self.unk_token_id def A_ ( self : Optional[Any], _UpperCAmelCase : int ) -> str: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(_UpperCAmelCase ) def A_ ( self : List[Any], _UpperCAmelCase : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = "" SCREAMING_SNAKE_CASE__ : str = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_UpperCAmelCase ) + token SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Optional[Any] = [] else: current_sub_tokens.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = False out_string += self.sp_model.decode(_UpperCAmelCase ) return out_string.strip() def __getstate__( self : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : List[str] = None return state def __setstate__( self : str, _UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = d # for backward compatibility if not hasattr(self, "sp_model_kwargs" ): SCREAMING_SNAKE_CASE__ : Tuple = {} SCREAMING_SNAKE_CASE__ : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A_ ( self : List[str], _UpperCAmelCase : str, _UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_UpperCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, _UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCAmelCase, "wb" ) as fi: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) return (out_vocab_file,)
663
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = '''Hello world! cécé herlolip''' def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = FairseqRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) roberta.eval() # disable dropout SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.sentence_encoder SCREAMING_SNAKE_CASE__ : List[str] = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaXLForSequenceClassification(SCREAMING_SNAKE_CASE__ ) if classification_head else XLMRobertaXLForMaskedLM(SCREAMING_SNAKE_CASE__ ) model.eval() # Now let's copy all the weights. # Embeddings SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.embed_tokens.weight SCREAMING_SNAKE_CASE__ : str = roberta_sent_encoder.embed_positions.weight SCREAMING_SNAKE_CASE__ : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. SCREAMING_SNAKE_CASE__ : Any = roberta_sent_encoder.layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer SCREAMING_SNAKE_CASE__ : BertLayer = model.roberta.encoder.layer[i] SCREAMING_SNAKE_CASE__ : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] SCREAMING_SNAKE_CASE__ : RobertaAttention = layer.attention SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn_layer_norm.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn_layer_norm.bias # self attention SCREAMING_SNAKE_CASE__ : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = roberta_layer.self_attn.q_proj.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.self_attn.q_proj.bias SCREAMING_SNAKE_CASE__ : Any = roberta_layer.self_attn.k_proj.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn.k_proj.bias SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.self_attn.v_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.self_attn.v_proj.bias # self-attention output SCREAMING_SNAKE_CASE__ : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.weight SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.bias # this one is final layer norm SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.bias # intermediate SCREAMING_SNAKE_CASE__ : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.bias # output SCREAMING_SNAKE_CASE__ : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.fca.bias # end of layer if classification_head: SCREAMING_SNAKE_CASE__ : str = roberta.model.classification_heads["mnli"].dense.weight SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"].dense.bias SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head SCREAMING_SNAKE_CASE__ : Tuple = roberta.model.encoder.lm_head.dense.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.dense.bias SCREAMING_SNAKE_CASE__ : List[str] = roberta.model.encoder.lm_head.layer_norm.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta.model.encoder.lm_head.layer_norm.bias SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.encoder.lm_head.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. SCREAMING_SNAKE_CASE__ : torch.Tensor = roberta.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) # batch of size 1 SCREAMING_SNAKE_CASE__ : int = model(SCREAMING_SNAKE_CASE__ )[0] if classification_head: SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"](roberta.extract_features(SCREAMING_SNAKE_CASE__ ) ) else: SCREAMING_SNAKE_CASE__ : int = roberta.model(SCREAMING_SNAKE_CASE__ )[0] print(our_output.shape , their_output.shape ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(f'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 SCREAMING_SNAKE_CASE__ : int = torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(SCREAMING_SNAKE_CASE__ ).mkdir(parents=SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_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.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) _lowerCamelCase : Any = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
663
1
import argparse import json import subprocess def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = ( f'''curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"''' " https://api.github.com/repos/huggingface/transformers/actions/runners" ) SCREAMING_SNAKE_CASE__ : List[Any] = subprocess.run(SCREAMING_SNAKE_CASE__ , shell=SCREAMING_SNAKE_CASE__ , stdout=subprocess.PIPE ) SCREAMING_SNAKE_CASE__ : Any = output.stdout.decode("utf-8" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.loads(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = status["runners"] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(SCREAMING_SNAKE_CASE__ ) # save the result so we can report them on Slack with open("offline_runners.txt" , "w" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) if len(SCREAMING_SNAKE_CASE__ ) > 0: SCREAMING_SNAKE_CASE__ : Dict = "\n".join([x["name"] for x in offline_runners] ) raise ValueError(f'''The following runners are offline:\n{failed}''' ) if __name__ == "__main__": def _a ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: '''simple docstring''' return values.split("," ) _lowerCamelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--target_runners''', default=None, type=list_str, required=True, help='''Comma-separated list of runners to check status.''', ) parser.add_argument( '''--token''', default=None, type=str, required=True, help='''A token that has actions:read permission.''' ) _lowerCamelCase : str = parser.parse_args() get_runner_status(args.target_runners, args.token)
663
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "Wav2Vec2FeatureExtractor" UpperCAmelCase_ = "AutoTokenizer" def __init__( self : Tuple, _UpperCAmelCase : Dict, _UpperCAmelCase : Tuple ) -> List[str]: """simple docstring""" super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extractor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False @classmethod def A_ ( cls : int, _UpperCAmelCase : Dict, **_UpperCAmelCase : List[Any] ) -> Optional[int]: """simple docstring""" try: return super().from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) except OSError: warnings.warn( F'''Loading a tokenizer inside {cls.__name__} from a config that does not''' " include a `tokenizer_class` attribute is deprecated and will be " "removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`" " attribute to either your `config.json` or `tokenizer_config.json` " "file to suppress this warning: ", _UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaFeatureExtractor.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = WavaVecaCTCTokenizer.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) return cls(feature_extractor=_UpperCAmelCase, tokenizer=_UpperCAmelCase ) def __call__( self : Optional[Any], *_UpperCAmelCase : int, **_UpperCAmelCase : str ) -> Optional[Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) if "raw_speech" in kwargs: warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead." ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("raw_speech" ) else: SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop("audio", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("sampling_rate", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : Tuple = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if audio is not None: SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor(_UpperCAmelCase, *_UpperCAmelCase, sampling_rate=_UpperCAmelCase, **_UpperCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE__ : List[str] = encodings["input_ids"] return inputs def A_ ( self : Optional[Any], *_UpperCAmelCase : List[str], **_UpperCAmelCase : Optional[int] ) -> Optional[int]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("input_features", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop("labels", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : Dict = args[1:] if input_features is not None: SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor.pad(_UpperCAmelCase, *_UpperCAmelCase, **_UpperCAmelCase ) if labels is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.pad(_UpperCAmelCase, **_UpperCAmelCase ) if labels is None: return input_features elif input_features is None: return labels else: SCREAMING_SNAKE_CASE__ : List[str] = labels["input_ids"] return input_features def A_ ( self : Union[str, Any], *_UpperCAmelCase : str, **_UpperCAmelCase : Any ) -> Optional[int]: """simple docstring""" return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Optional[int], *_UpperCAmelCase : Tuple, **_UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) @contextmanager def A_ ( self : Optional[int] ) -> Any: """simple docstring""" warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your audio inputs, or in a separate call." ) SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : int = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extractor SCREAMING_SNAKE_CASE__ : Optional[Any] = False
663
1
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class lowerCamelCase : """simple docstring""" @property def A_ ( self : Any ) -> Optional[Any]: """simple docstring""" return self.get_dummy_input() @property def A_ ( self : Any ) -> Any: """simple docstring""" if self.block_type == "down": return (4, 3_2, 1_6, 1_6) elif self.block_type == "mid": return (4, 3_2, 3_2, 3_2) elif self.block_type == "up": return (4, 3_2, 6_4, 6_4) raise ValueError(F'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.''' ) def A_ ( self : Any, _UpperCAmelCase : Union[str, Any]=True, _UpperCAmelCase : Union[str, Any]=False, _UpperCAmelCase : Optional[int]=False, _UpperCAmelCase : Optional[int]=False, ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = 3_2 SCREAMING_SNAKE_CASE__ : int = (3_2, 3_2) SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.device(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = (batch_size, num_channels) + sizes SCREAMING_SNAKE_CASE__ : Tuple = randn_tensor(_UpperCAmelCase, generator=_UpperCAmelCase, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = {"hidden_states": hidden_states} if include_temb: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_2_8 SCREAMING_SNAKE_CASE__ : Dict = randn_tensor((batch_size, temb_channels), generator=_UpperCAmelCase, device=_UpperCAmelCase ) if include_res_hidden_states_tuple: SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(1 ) SCREAMING_SNAKE_CASE__ : str = (randn_tensor(_UpperCAmelCase, generator=_UpperCAmelCase, device=_UpperCAmelCase ),) if include_encoder_hidden_states: SCREAMING_SNAKE_CASE__ : Any = floats_tensor((batch_size, 3_2, 3_2) ).to(_UpperCAmelCase ) if include_skip_sample: SCREAMING_SNAKE_CASE__ : List[str] = randn_tensor(((batch_size, 3) + sizes), generator=_UpperCAmelCase, device=_UpperCAmelCase ) return dummy_input def A_ ( self : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "in_channels": 3_2, "out_channels": 3_2, "temb_channels": 1_2_8, } if self.block_type == "up": SCREAMING_SNAKE_CASE__ : Optional[int] = 3_2 if self.block_type == "mid": init_dict.pop("out_channels" ) SCREAMING_SNAKE_CASE__ : Dict = self.dummy_input return init_dict, inputs_dict def A_ ( self : Tuple, _UpperCAmelCase : List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = self.block_class(**_UpperCAmelCase ) unet_block.to(_UpperCAmelCase ) unet_block.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = unet_block(**_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = output[0] self.assertEqual(output.shape, self.output_shape ) SCREAMING_SNAKE_CASE__ : List[str] = output[0, -1, -3:, -3:] SCREAMING_SNAKE_CASE__ : Any = torch.tensor(_UpperCAmelCase ).to(_UpperCAmelCase ) assert torch_all_close(output_slice.flatten(), _UpperCAmelCase, atol=5E-3 ) @unittest.skipIf(torch_device == "mps", "Training is not supported in mps" ) def A_ ( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Any = self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = self.block_class(**_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.train() SCREAMING_SNAKE_CASE__ : List[str] = model(**_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : str = output[0] SCREAMING_SNAKE_CASE__ : Tuple = torch.device(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = randn_tensor(output.shape, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = torch.nn.functional.mse_loss(_UpperCAmelCase, _UpperCAmelCase ) loss.backward()
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Tuple = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowerCamelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
663
1
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 lowerCamelCase (unittest.TestCase ): """simple docstring""" @property def A_ ( self : List[Any] ) -> str: """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ort.SessionOptions() SCREAMING_SNAKE_CASE__ : Any = False return options def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo.png" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo_mask.png" ) SCREAMING_SNAKE_CASE__ : List[str] = 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 SCREAMING_SNAKE_CASE__ : Tuple = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="onnx", safety_checker=_UpperCAmelCase, feature_extractor=_UpperCAmelCase, provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = "A red cat sitting on a park bench" SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.RandomState(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_UpperCAmelCase, image=_UpperCAmelCase, mask_image=_UpperCAmelCase, strength=0.75, guidance_scale=7.5, num_inference_steps=1_5, generator=_UpperCAmelCase, output_type="np", ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 1E-2
663
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = '''▁''' _lowerCamelCase : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''monolingual_vocab_file''': '''dict.txt'''} _lowerCamelCase : Dict = { '''vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model''', }, '''monolingual_vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt''', }, } _lowerCamelCase : Optional[Any] = {'''vinai/bartpho-syllable''': 1_0_2_4} class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = ["input_ids", "attention_mask"] def __init__( self : int, _UpperCAmelCase : Dict, _UpperCAmelCase : Tuple, _UpperCAmelCase : Any="<s>", _UpperCAmelCase : List[str]="</s>", _UpperCAmelCase : List[str]="</s>", _UpperCAmelCase : List[Any]="<s>", _UpperCAmelCase : Dict="<unk>", _UpperCAmelCase : Tuple="<pad>", _UpperCAmelCase : int="<mask>", _UpperCAmelCase : Optional[Dict[str, Any]] = None, **_UpperCAmelCase : Any, ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Any = AddedToken(_UpperCAmelCase, lstrip=_UpperCAmelCase, rstrip=_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ) else mask_token SCREAMING_SNAKE_CASE__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCAmelCase, eos_token=_UpperCAmelCase, unk_token=_UpperCAmelCase, sep_token=_UpperCAmelCase, cls_token=_UpperCAmelCase, pad_token=_UpperCAmelCase, mask_token=_UpperCAmelCase, sp_model_kwargs=self.sp_model_kwargs, **_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_file SCREAMING_SNAKE_CASE__ : Optional[int] = monolingual_vocab_file SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_UpperCAmelCase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_UpperCAmelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : Dict = cnt cnt += 1 with open(_UpperCAmelCase, "r", encoding="utf-8" ) as f: for line in f.readlines(): SCREAMING_SNAKE_CASE__ : int = line.strip().split()[0] SCREAMING_SNAKE_CASE__ : Tuple = len(self.fairseq_tokens_to_ids ) if str(_UpperCAmelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : List[Any] = len(self.fairseq_tokens_to_ids ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : int = self.sp_model.serialized_model_proto() return state def __setstate__( self : int, _UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = d # for backward compatibility if not hasattr(self, "sp_model_kwargs" ): SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def A_ ( self : Optional[int], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Any = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : List[str], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None, _UpperCAmelCase : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase, token_ids_a=_UpperCAmelCase, already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1, 1] + ([0] * len(_UpperCAmelCase )) + [1] def A_ ( self : Optional[int], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A_ ( self : Any ) -> List[str]: """simple docstring""" return len(self.fairseq_ids_to_tokens ) def A_ ( self : Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = {self.convert_ids_to_tokens(_UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : Tuple, _UpperCAmelCase : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_UpperCAmelCase, out_type=_UpperCAmelCase ) def A_ ( self : List[str], _UpperCAmelCase : Union[str, Any] ) -> Tuple: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def A_ ( self : List[str], _UpperCAmelCase : str ) -> str: """simple docstring""" return self.fairseq_ids_to_tokens[index] def A_ ( self : Optional[Any], _UpperCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "".join(_UpperCAmelCase ).replace(_UpperCAmelCase, " " ).strip() return out_string def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_UpperCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["monolingual_vocab_file"], ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, _UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCAmelCase, "wb" ) as fi: SCREAMING_SNAKE_CASE__ : int = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _UpperCAmelCase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file, _UpperCAmelCase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_UpperCAmelCase, "w", encoding="utf-8" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F'''{str(_UpperCAmelCase )} \n''' ) return out_vocab_file, out_monolingual_vocab_file
663
1
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch _lowerCamelCase : Dict = random.Random() def _a ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=1.0 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None ) -> Any: '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : int = global_rng SCREAMING_SNAKE_CASE__ : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" def __init__( self : str, _UpperCAmelCase : List[str], _UpperCAmelCase : List[str]=7, _UpperCAmelCase : Tuple=4_0_0, _UpperCAmelCase : Any=2_0_0_0, _UpperCAmelCase : str=1, _UpperCAmelCase : Tuple=0.0, _UpperCAmelCase : Optional[Any]=1_6_0_0_0, _UpperCAmelCase : List[Any]=True, _UpperCAmelCase : int=8_0, _UpperCAmelCase : Dict=1_6, _UpperCAmelCase : Optional[int]=6_4, _UpperCAmelCase : int="hann_window", _UpperCAmelCase : int=8_0, _UpperCAmelCase : List[str]=7_6_0_0, _UpperCAmelCase : Optional[int]=1E-10, _UpperCAmelCase : Optional[int]=True, ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : Dict = feature_size SCREAMING_SNAKE_CASE__ : List[Any] = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : List[str] = do_normalize SCREAMING_SNAKE_CASE__ : List[str] = num_mel_bins SCREAMING_SNAKE_CASE__ : Optional[Any] = hop_length SCREAMING_SNAKE_CASE__ : List[Any] = win_length SCREAMING_SNAKE_CASE__ : List[Any] = win_function SCREAMING_SNAKE_CASE__ : Any = fmin SCREAMING_SNAKE_CASE__ : Optional[Any] = fmax SCREAMING_SNAKE_CASE__ : List[str] = mel_floor SCREAMING_SNAKE_CASE__ : Optional[int] = return_attention_mask def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def A_ ( self : Dict, _UpperCAmelCase : str=False, _UpperCAmelCase : Any=False ) -> int: """simple docstring""" def _flatten(_UpperCAmelCase : Any ): return list(itertools.chain(*_UpperCAmelCase ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Any = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[Any] = [ _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__ : List[Any] = [np.asarray(_UpperCAmelCase ) for x in speech_inputs] return speech_inputs def A_ ( self : Any, _UpperCAmelCase : Union[str, Any]=False, _UpperCAmelCase : Dict=False ) -> Optional[Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : Any = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[Any] = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : Tuple = [np.asarray(_UpperCAmelCase ) for x in speech_inputs] return speech_inputs @require_torch class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = SpeechTaFeatureExtractor def A_ ( self : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractionTester(self ) def A_ ( self : Dict, _UpperCAmelCase : int ) -> Union[str, Any]: """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 : Dict ) -> str: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[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__ : int = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(_UpperCAmelCase ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = feat_extract(speech_inputs[0], return_tensors="np" ).input_values SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(np_speech_inputs[0], return_tensors="np" ).input_values self.assertTrue(np.allclose(_UpperCAmelCase, _UpperCAmelCase, atol=1E-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract(_UpperCAmelCase, return_tensors="np" ).input_values SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] SCREAMING_SNAKE_CASE__ : Tuple = ["longest", "max_length", "do_not_pad"] SCREAMING_SNAKE_CASE__ : Optional[int] = [None, 1_6_0_0, None] for max_length, padding in zip(_UpperCAmelCase, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : int = feat_extract(_UpperCAmelCase, padding=_UpperCAmelCase, max_length=_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = 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 : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = range(8_0_0, 1_4_0_0, 2_0_0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["longest", "max_length", "do_not_pad"] SCREAMING_SNAKE_CASE__ : Any = [None, 1_6_0_0, None] for max_length, padding in zip(_UpperCAmelCase, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(_UpperCAmelCase, max_length=_UpperCAmelCase, padding=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = 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 ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract( _UpperCAmelCase, truncation=_UpperCAmelCase, max_length=1_0_0_0, padding="max_length", return_tensors="np" ) SCREAMING_SNAKE_CASE__ : List[str] = 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 : Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( _UpperCAmelCase, truncation=_UpperCAmelCase, max_length=1_0_0_0, padding="longest", return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Dict = 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) ) SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract( _UpperCAmelCase, truncation=_UpperCAmelCase, max_length=2_0_0_0, padding="longest", return_tensors="np" ) SCREAMING_SNAKE_CASE__ : List[Any] = 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) ) def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[str] = np.random.rand(1_0_0 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : Optional[int] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : List[Any] = feature_extractor.pad([{"input_values": inputs}], return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{"input_values": inputs}], return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] SCREAMING_SNAKE_CASE__ : Tuple = [np.asarray(_UpperCAmelCase ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Dict = feature_extractor(audio_target=_UpperCAmelCase, padding=_UpperCAmelCase, return_tensors="np" ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = feature_extractor(speech_inputs[0], return_tensors="np" ).input_values SCREAMING_SNAKE_CASE__ : Any = feature_extractor(np_speech_inputs[0], return_tensors="np" ).input_values self.assertTrue(np.allclose(_UpperCAmelCase, _UpperCAmelCase, atol=1E-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Any = feature_extractor(_UpperCAmelCase, return_tensors="np" ).input_values SCREAMING_SNAKE_CASE__ : List[Any] = feature_extractor(_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. SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] SCREAMING_SNAKE_CASE__ : Any = np.asarray(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feature_extractor(_UpperCAmelCase, return_tensors="np" ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(_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 : Tuple ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_UpperCAmelCase ) == len(_UpperCAmelCase ) for x, y in zip(_UpperCAmelCase, processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs}, tensor_type="np" ) SCREAMING_SNAKE_CASE__ : int = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : str = BatchFeature({input_name: speech_inputs}, tensor_type="pt" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Tuple = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def A_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : str = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Dict = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad(_UpperCAmelCase, padding="longest", return_tensors="np" )[input_name] SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract.pad(_UpperCAmelCase, padding="longest", return_tensors="pt" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def A_ ( self : List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extraction_class(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(_UpperCAmelCase ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : int = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(_UpperCAmelCase, padding="longest", return_tensors="np" ) self.assertIn("attention_mask", _UpperCAmelCase ) self.assertListEqual(list(processed.attention_mask.shape ), list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist(), _UpperCAmelCase ) def A_ ( self : str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[str] = [len(_UpperCAmelCase ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = min(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( _UpperCAmelCase, padding="max_length", max_length=_UpperCAmelCase, truncation=_UpperCAmelCase, return_tensors="np" ) self.assertIn("attention_mask", _UpperCAmelCase ) self.assertListEqual( list(processed_pad.attention_mask.shape ), [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist(), [max_length for x in speech_inputs] ) def A_ ( self : str, _UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : Any = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : Optional[int] = ds.sort("id" ).select(range(_UpperCAmelCase ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def A_ ( self : Dict ) -> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [2.3804E-03, 2.0752E-03, 1.9836E-03, 2.1057E-03, 1.6174E-03, 3.0518E-04, 9.1553E-05, 3.3569E-04, 9.7656E-04, 1.8311E-03, 2.0142E-03, 2.1057E-03, 1.7395E-03, 4.5776E-04, -3.9673E-04, 4.5776E-04, 1.0071E-03, 9.1553E-05, 4.8828E-04, 1.1597E-03, 7.3242E-04, 9.4604E-04, 1.8005E-03, 1.8311E-03, 8.8501E-04, 4.2725E-04, 4.8828E-04, 7.3242E-04, 1.0986E-03, 2.1057E-03] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : int = feature_extractor(_UpperCAmelCase, return_tensors="pt" ).input_values self.assertEquals(input_values.shape, (1, 9_3_6_8_0) ) self.assertTrue(torch.allclose(input_values[0, :3_0], _UpperCAmelCase, atol=1E-6 ) ) def A_ ( self : int ) -> Any: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Tuple = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : List[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = feature_extractor(audio_target=_UpperCAmelCase, return_tensors="pt" ).input_values self.assertEquals(input_values.shape, (1, 3_6_6, 8_0) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0], _UpperCAmelCase, atol=1E-4 ) )
663
from random import shuffle import tensorflow as tf from numpy import array def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = int(SCREAMING_SNAKE_CASE__ ) assert noofclusters < len(SCREAMING_SNAKE_CASE__ ) # Find out the dimensionality SCREAMING_SNAKE_CASE__ : List[Any] = len(vectors[0] ) # Will help select random centroids from among the available vectors SCREAMING_SNAKE_CASE__ : List[Any] = list(range(len(SCREAMING_SNAKE_CASE__ ) ) ) shuffle(SCREAMING_SNAKE_CASE__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. SCREAMING_SNAKE_CASE__ : Tuple = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION SCREAMING_SNAKE_CASE__ : List[Any] = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points SCREAMING_SNAKE_CASE__ : Any = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(SCREAMING_SNAKE_CASE__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("float64" , [dim] ) SCREAMING_SNAKE_CASE__ : Dict = [] for centroid in centroids: cent_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) SCREAMING_SNAKE_CASE__ : Tuple = [tf.Variable(0 ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value SCREAMING_SNAKE_CASE__ : Tuple = tf.placeholder("int32" ) SCREAMING_SNAKE_CASE__ : Tuple = [] for assignment in assignments: cluster_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input SCREAMING_SNAKE_CASE__ : int = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors SCREAMING_SNAKE_CASE__ : str = tf.reduce_mean(SCREAMING_SNAKE_CASE__ , 0 ) ##Node for computing Euclidean distances # Placeholders for input SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.placeholder("float" , [dim] ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("float" , [dim] ) SCREAMING_SNAKE_CASE__ : Dict = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.placeholder("float" , [noofclusters] ) SCREAMING_SNAKE_CASE__ : Tuple = tf.argmin(SCREAMING_SNAKE_CASE__ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. SCREAMING_SNAKE_CASE__ : Tuple = tf.initialize_all_variables() # Initialize all variables sess.run(SCREAMING_SNAKE_CASE__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. SCREAMING_SNAKE_CASE__ : Tuple = 1_00 for _ in range(SCREAMING_SNAKE_CASE__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(SCREAMING_SNAKE_CASE__ ) ): SCREAMING_SNAKE_CASE__ : Any = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. SCREAMING_SNAKE_CASE__ : Tuple = [ sess.run(SCREAMING_SNAKE_CASE__ , feed_dict={va: vect, va: sess.run(SCREAMING_SNAKE_CASE__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input SCREAMING_SNAKE_CASE__ : Any = sess.run( SCREAMING_SNAKE_CASE__ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(SCREAMING_SNAKE_CASE__ ): # Collect all the vectors assigned to this cluster SCREAMING_SNAKE_CASE__ : Dict = [ vectors[i] for i in range(len(SCREAMING_SNAKE_CASE__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location SCREAMING_SNAKE_CASE__ : str = sess.run( SCREAMING_SNAKE_CASE__ , feed_dict={mean_input: array(SCREAMING_SNAKE_CASE__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments SCREAMING_SNAKE_CASE__ : int = sess.run(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = sess.run(SCREAMING_SNAKE_CASE__ ) return centroids, assignments
663
1
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class lowerCamelCase (__lowerCamelCase , __lowerCamelCase ): """simple docstring""" @register_to_config def __init__( self : Union[str, Any], _UpperCAmelCase : int = 7_6_8, ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : str = nn.Parameter(torch.zeros(1, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = nn.Parameter(torch.ones(1, _UpperCAmelCase ) ) def A_ ( self : Dict, _UpperCAmelCase : Optional[Union[str, torch.device]] = None, _UpperCAmelCase : Optional[torch.dtype] = None, ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = nn.Parameter(self.mean.to(_UpperCAmelCase ).to(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = nn.Parameter(self.std.to(_UpperCAmelCase ).to(_UpperCAmelCase ) ) return self def A_ ( self : Union[str, Any], _UpperCAmelCase : Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = (embeds - self.mean) * 1.0 / self.std return embeds def A_ ( self : List[Any], _UpperCAmelCase : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = (embeds * self.std) + self.mean return embeds
663
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) _lowerCamelCase : List[str] = None _lowerCamelCase : Union[str, Any] = { '''7B''': 1_1_0_0_8, '''13B''': 1_3_8_2_4, '''30B''': 1_7_9_2_0, '''65B''': 2_2_0_1_6, '''70B''': 2_8_6_7_2, } _lowerCamelCase : Optional[Any] = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : str=2_56 ) -> int: '''simple docstring''' return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def _a ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ , "r" ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str=True ) -> int: '''simple docstring''' os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , "tmp" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = read_json(os.path.join(SCREAMING_SNAKE_CASE__ , "params.json" ) ) SCREAMING_SNAKE_CASE__ : int = NUM_SHARDS[model_size] SCREAMING_SNAKE_CASE__ : Union[str, Any] = params["n_layers"] SCREAMING_SNAKE_CASE__ : List[str] = params["n_heads"] SCREAMING_SNAKE_CASE__ : Optional[Any] = n_heads // num_shards SCREAMING_SNAKE_CASE__ : str = params["dim"] SCREAMING_SNAKE_CASE__ : List[str] = dim // n_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_0_0_0_0.0 SCREAMING_SNAKE_CASE__ : Tuple = 1.0 / (base ** (torch.arange(0 , SCREAMING_SNAKE_CASE__ , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: SCREAMING_SNAKE_CASE__ : int = params["n_kv_heads"] # for GQA / MQA SCREAMING_SNAKE_CASE__ : Optional[int] = n_heads_per_shard // num_key_value_heads SCREAMING_SNAKE_CASE__ : int = dim // num_key_value_heads else: # compatibility with other checkpoints SCREAMING_SNAKE_CASE__ : Dict = n_heads SCREAMING_SNAKE_CASE__ : str = n_heads_per_shard SCREAMING_SNAKE_CASE__ : Dict = dim # permute for sliced rotary def permute(SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=n_heads , SCREAMING_SNAKE_CASE__ : List[str]=dim , SCREAMING_SNAKE_CASE__ : Dict=dim ): return w.view(SCREAMING_SNAKE_CASE__ , dima // n_heads // 2 , 2 , SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'''Fetching all parameters from the checkpoint at {input_base_path}.''' ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) SCREAMING_SNAKE_CASE__ : Dict = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , "consolidated.00.pth" ) , map_location="cpu" ) else: # Sharded SCREAMING_SNAKE_CASE__ : List[Any] = [ torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , f'''consolidated.{i:02d}.pth''' ) , map_location="cpu" ) for i in range(SCREAMING_SNAKE_CASE__ ) ] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : List[str] = {"weight_map": {}} for layer_i in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded SCREAMING_SNAKE_CASE__ : List[Any] = { f'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wq.weight'''] ), f'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wk.weight'''] ), f'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[f'''layers.{layer_i}.attention.wv.weight'''], f'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[f'''layers.{layer_i}.attention.wo.weight'''], f'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w1.weight'''], f'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w2.weight'''], f'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w3.weight'''], f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[f'''layers.{layer_i}.attention_norm.weight'''], f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[f'''layers.{layer_i}.ffn_norm.weight'''], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. SCREAMING_SNAKE_CASE__ : Any = { f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.attention_norm.weight''' ].clone(), f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.ffn_norm.weight''' ].clone(), } SCREAMING_SNAKE_CASE__ : int = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wq.weight'''].view(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : Tuple = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wk.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wv.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = torch.cat( [loaded[i][f'''layers.{layer_i}.attention.wo.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : int = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) SCREAMING_SNAKE_CASE__ : List[str] = inv_freq for k, v in state_dict.items(): SCREAMING_SNAKE_CASE__ : str = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded SCREAMING_SNAKE_CASE__ : List[str] = { "model.embed_tokens.weight": loaded["tok_embeddings.weight"], "model.norm.weight": loaded["norm.weight"], "lm_head.weight": loaded["output.weight"], } else: SCREAMING_SNAKE_CASE__ : Optional[Any] = { "model.norm.weight": loaded[0]["norm.weight"], "model.embed_tokens.weight": torch.cat( [loaded[i]["tok_embeddings.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ), "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ), } for k, v in state_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[int] = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Write configs SCREAMING_SNAKE_CASE__ : Optional[Any] = {"total_size": param_count * 2} write_json(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , "pytorch_model.bin.index.json" ) ) SCREAMING_SNAKE_CASE__ : List[str] = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1 SCREAMING_SNAKE_CASE__ : Dict = params["multiple_of"] if "multiple_of" in params else 2_56 SCREAMING_SNAKE_CASE__ : Dict = LlamaConfig( hidden_size=SCREAMING_SNAKE_CASE__ , intermediate_size=compute_intermediate_size(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , num_attention_heads=params["n_heads"] , num_hidden_layers=params["n_layers"] , rms_norm_eps=params["norm_eps"] , num_key_value_heads=SCREAMING_SNAKE_CASE__ , ) config.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("Loading the checkpoint in a Llama model." ) SCREAMING_SNAKE_CASE__ : int = LlamaForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa , low_cpu_mem_usage=SCREAMING_SNAKE_CASE__ ) # Avoid saving this as part of the config. del model.config._name_or_path print("Saving in the Transformers format." ) model.save_pretrained(SCREAMING_SNAKE_CASE__ , safe_serialization=SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(f'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer_class(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() parser.add_argument( "--input_dir" , help="Location of LLaMA weights, which contains tokenizer.model and model folders" , ) parser.add_argument( "--model_size" , choices=["7B", "7Bf", "13B", "13Bf", "30B", "65B", "70B", "70Bf", "tokenizer_only"] , ) parser.add_argument( "--output_dir" , help="Location to write HF model and tokenizer" , ) parser.add_argument("--safe_serialization" , type=SCREAMING_SNAKE_CASE__ , help="Whether or not to save using `safetensors`." ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(args.input_dir , "tokenizer.model" ) write_tokenizer(args.output_dir , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
663
1
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase (unittest.TestCase ): """simple docstring""" def __init__( self : Tuple, _UpperCAmelCase : Tuple, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : Tuple=3_2, _UpperCAmelCase : Optional[Any]=3, _UpperCAmelCase : Tuple=1_0, _UpperCAmelCase : Tuple=[1_0, 2_0, 3_0, 4_0], _UpperCAmelCase : str=[1, 1, 2, 1], _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Dict=True, _UpperCAmelCase : int="relu", _UpperCAmelCase : Optional[Any]=3, _UpperCAmelCase : Tuple=None, ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Tuple = image_size SCREAMING_SNAKE_CASE__ : str = num_channels SCREAMING_SNAKE_CASE__ : Any = embeddings_size SCREAMING_SNAKE_CASE__ : Dict = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = depths SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : Tuple = use_labels SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : int = num_labels SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : List[str] = len(_UpperCAmelCase ) def A_ ( self : Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values def A_ ( self : int ) -> Union[str, Any]: """simple docstring""" return RegNetConfig( num_channels=self.num_channels, embeddings_size=self.embeddings_size, hidden_sizes=self.hidden_sizes, depths=self.depths, hidden_act=self.hidden_act, num_labels=self.num_labels, image_size=self.image_size, ) def A_ ( self : Dict, _UpperCAmelCase : int, _UpperCAmelCase : Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FlaxRegNetModel(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = model(_UpperCAmelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2), ) def A_ ( self : Tuple, _UpperCAmelCase : List[str], _UpperCAmelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxRegNetForImageClassification(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[int] = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = FlaxRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self, config_class=_UpperCAmelCase, has_text_modality=_UpperCAmelCase ) def A_ ( self : Dict ) -> Tuple: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A_ ( self : List[str] ) -> List[Any]: """simple docstring""" return def A_ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @unittest.skip(reason="RegNet does not use inputs_embeds" ) def A_ ( self : Optional[Any] ) -> str: """simple docstring""" pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def A_ ( self : Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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__ : Optional[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" def check_hidden_states_output(_UpperCAmelCase : int, _UpperCAmelCase : Dict, _UpperCAmelCase : str ): SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = model(**self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[str] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.num_stages self.assertEqual(len(_UpperCAmelCase ), expected_num_stages + 1 ) 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: SCREAMING_SNAKE_CASE__ : List[str] = True check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Optional[Any] = True check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[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__ : Union[str, Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = model_class(_UpperCAmelCase ) @jax.jit def model_jitted(_UpperCAmelCase : str, **_UpperCAmelCase : int ): return model(pixel_values=_UpperCAmelCase, **_UpperCAmelCase ) with self.subTest("JIT Enabled" ): SCREAMING_SNAKE_CASE__ : List[str] = model_jitted(**_UpperCAmelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE__ : List[str] = model_jitted(**_UpperCAmelCase ).to_tuple() self.assertEqual(len(_UpperCAmelCase ), len(_UpperCAmelCase ) ) for jitted_output, output in zip(_UpperCAmelCase, _UpperCAmelCase ): self.assertEqual(jitted_output.shape, output.shape ) def _a ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_flax class lowerCamelCase (unittest.TestCase ): """simple docstring""" @cached_property def A_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" return AutoImageProcessor.from_pretrained("facebook/regnet-y-040" ) if is_vision_available() else None @slow def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040" ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(images=_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**_UpperCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE__ : List[str] = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3], _UpperCAmelCase, atol=1E-4 ) )
663
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = GPTaTokenizer UpperCAmelCase_ = GPTaTokenizerFast UpperCAmelCase_ = True UpperCAmelCase_ = {"add_prefix_space": True} UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : Any = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] SCREAMING_SNAKE_CASE__ : int = dict(zip(_UpperCAmelCase, range(len(_UpperCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE__ : str = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] SCREAMING_SNAKE_CASE__ : Any = {"unk_token": "<unk>"} SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file, "w", encoding="utf-8" ) as fp: fp.write(json.dumps(_UpperCAmelCase ) + "\n" ) with open(self.merges_file, "w", encoding="utf-8" ) as fp: fp.write("\n".join(_UpperCAmelCase ) ) def A_ ( self : Tuple, **_UpperCAmelCase : str ) -> str: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : int, **_UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : Tuple, _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = "lower newer" SCREAMING_SNAKE_CASE__ : List[Any] = "lower newer" return input_text, output_text def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Tuple = "lower newer" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] SCREAMING_SNAKE_CASE__ : Dict = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Dict = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Dict ) -> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = "lower newer" # Testing tokenization SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE__ : Tuple = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing the unknown token SCREAMING_SNAKE_CASE__ : Dict = tokens + [rust_tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : str = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Tuple, *_UpperCAmelCase : List[Any], **_UpperCAmelCase : Union[str, Any] ) -> Optional[int]: """simple docstring""" # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def A_ ( self : Optional[Any], _UpperCAmelCase : int=1_5 ) -> List[str]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Any = self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) # Simple input SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : List[str] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Any = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : List[Any] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) def A_ ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = GPTaTokenizer.from_pretrained(self.tmpdirname, pad_token="<pad>" ) # Simple input SCREAMING_SNAKE_CASE__ : Union[str, Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Dict = ["This is a simple input looooooooong", "This is a simple input"] SCREAMING_SNAKE_CASE__ : List[str] = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : int = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding="max_length", max_length=3_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(*_UpperCAmelCase, padding="max_length", max_length=6_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1], 3_0 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1], 3_3 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1], 6_0 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1], 5_2 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "$$$" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer.from_pretrained(self.tmpdirname, bos_token=_UpperCAmelCase, add_bos_token=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(_UpperCAmelCase ) self.assertEqual(out_s.input_ids[0], _UpperCAmelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.decode(out_s.input_ids ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], _UpperCAmelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def A_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" pass def A_ ( self : Dict ) -> str: """simple docstring""" # TODO: change to self.get_tokenizers() when the fast version is implemented SCREAMING_SNAKE_CASE__ : Any = [self.get_tokenizer(do_lower_case=_UpperCAmelCase, add_bos_token=_UpperCAmelCase )] for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ : List[Any] = "Encode this." SCREAMING_SNAKE_CASE__ : Optional[Any] = "This one too please." SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) encoded_sequence += tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode_plus( _UpperCAmelCase, _UpperCAmelCase, add_special_tokens=_UpperCAmelCase, return_special_tokens_mask=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(_UpperCAmelCase ), len(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(_UpperCAmelCase ) ] SCREAMING_SNAKE_CASE__ : List[Any] = [x for x in filtered_sequence if x is not None] self.assertEqual(_UpperCAmelCase, _UpperCAmelCase ) @require_tokenizers class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Optional[Any] ) -> int: """simple docstring""" # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("test_opt" ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("./test_opt" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", use_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = "A photo of a cat" SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode( _UpperCAmelCase, ) # Same as above self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) @unittest.skip("This test is failing because of a bug in the fast tokenizer" ) def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = "bos" SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.get_vocab()["bos"] SCREAMING_SNAKE_CASE__ : Tuple = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode( _UpperCAmelCase, ) # We changed the bos token self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("./tok" ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained("./tok" ) self.assertTrue(tokenizer.is_fast ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] )
663
1
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values _lowerCamelCase : int = argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') _lowerCamelCase , _lowerCamelCase : str = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') _lowerCamelCase : Dict = rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: _lowerCamelCase : str = rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) _lowerCamelCase : str = args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"pip install -r transformers/examples/{example_dir}/requirements.txt"]) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}"]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
663
from functools import lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> set: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(SCREAMING_SNAKE_CASE__ ) if n > 1: factors.add(SCREAMING_SNAKE_CASE__ ) return factors @lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' return len(unique_prime_factors(SCREAMING_SNAKE_CASE__ ) ) def _a ( SCREAMING_SNAKE_CASE__ : list ) -> bool: '''simple docstring''' return len(set(SCREAMING_SNAKE_CASE__ ) ) in (0, 1) def _a ( SCREAMING_SNAKE_CASE__ : int ) -> list: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 2 while True: # Increment each value of a generated range SCREAMING_SNAKE_CASE__ : List[str] = [base + i for i in range(SCREAMING_SNAKE_CASE__ )] # Run elements through out unique_prime_factors function # Append our target number to the end. SCREAMING_SNAKE_CASE__ : Tuple = [upf_len(SCREAMING_SNAKE_CASE__ ) for x in group] checker.append(SCREAMING_SNAKE_CASE__ ) # If all numbers in the list are equal, return the group variable. if equality(SCREAMING_SNAKE_CASE__ ): return group # Increment our base variable by 1 base += 1 def _a ( SCREAMING_SNAKE_CASE__ : int = 4 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = run(SCREAMING_SNAKE_CASE__ ) return results[0] if len(SCREAMING_SNAKE_CASE__ ) else None if __name__ == "__main__": print(solution())
663
1
import math from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : str = { '''facebook/data2vec-base-960h''': '''https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json''', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "data2vec-audio" def __init__( self : Optional[int], _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Tuple=7_6_8, _UpperCAmelCase : List[str]=1_2, _UpperCAmelCase : Optional[int]=1_2, _UpperCAmelCase : Any=3_0_7_2, _UpperCAmelCase : Dict="gelu", _UpperCAmelCase : Dict=0.1, _UpperCAmelCase : Any=0.1, _UpperCAmelCase : Union[str, Any]=0.1, _UpperCAmelCase : Optional[Any]=0.0, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Tuple=0.1, _UpperCAmelCase : str=0.02, _UpperCAmelCase : str=1E-5, _UpperCAmelCase : Union[str, Any]="gelu", _UpperCAmelCase : List[Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2), _UpperCAmelCase : Any=(5, 2, 2, 2, 2, 2, 2), _UpperCAmelCase : Tuple=(1_0, 3, 3, 3, 3, 2, 2), _UpperCAmelCase : Any=False, _UpperCAmelCase : Dict=1_6, _UpperCAmelCase : Optional[int]=1_9, _UpperCAmelCase : Dict=5, _UpperCAmelCase : int=0.05, _UpperCAmelCase : List[str]=1_0, _UpperCAmelCase : Union[str, Any]=2, _UpperCAmelCase : Any=0.0, _UpperCAmelCase : Dict=1_0, _UpperCAmelCase : Any=0, _UpperCAmelCase : Any="sum", _UpperCAmelCase : int=False, _UpperCAmelCase : str=False, _UpperCAmelCase : str=2_5_6, _UpperCAmelCase : int=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0), _UpperCAmelCase : List[str]=(5, 3, 3, 1, 1), _UpperCAmelCase : Optional[int]=(1, 2, 3, 1, 1), _UpperCAmelCase : int=5_1_2, _UpperCAmelCase : Union[str, Any]=0, _UpperCAmelCase : List[str]=1, _UpperCAmelCase : Union[str, Any]=2, _UpperCAmelCase : str=False, _UpperCAmelCase : Optional[Any]=3, _UpperCAmelCase : str=2, _UpperCAmelCase : Optional[Any]=3, _UpperCAmelCase : Any=None, **_UpperCAmelCase : Tuple, ) -> List[str]: """simple docstring""" super().__init__(**_UpperCAmelCase, pad_token_id=_UpperCAmelCase, bos_token_id=_UpperCAmelCase, eos_token_id=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract_activation SCREAMING_SNAKE_CASE__ : str = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = conv_bias SCREAMING_SNAKE_CASE__ : Optional[Any] = num_conv_pos_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE__ : Optional[int] = conv_pos_kernel_size SCREAMING_SNAKE_CASE__ : Optional[Any] = len(self.conv_dim ) SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : str = hidden_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = activation_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_proj_dropout SCREAMING_SNAKE_CASE__ : List[str] = final_dropout SCREAMING_SNAKE_CASE__ : Any = layerdrop SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE__ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = use_weighted_layer_sum 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 SCREAMING_SNAKE_CASE__ : Union[str, Any] = mask_time_prob SCREAMING_SNAKE_CASE__ : Tuple = mask_time_length SCREAMING_SNAKE_CASE__ : Optional[int] = mask_time_min_masks SCREAMING_SNAKE_CASE__ : Union[str, Any] = mask_feature_prob SCREAMING_SNAKE_CASE__ : int = mask_feature_length SCREAMING_SNAKE_CASE__ : List[str] = mask_feature_min_masks # ctc loss SCREAMING_SNAKE_CASE__ : List[str] = ctc_loss_reduction SCREAMING_SNAKE_CASE__ : Tuple = ctc_zero_infinity # adapter SCREAMING_SNAKE_CASE__ : Dict = add_adapter SCREAMING_SNAKE_CASE__ : List[Any] = adapter_kernel_size SCREAMING_SNAKE_CASE__ : Any = adapter_stride SCREAMING_SNAKE_CASE__ : Optional[Any] = num_adapter_layers SCREAMING_SNAKE_CASE__ : Tuple = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE__ : List[str] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE__ : Optional[int] = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = xvector_output_dim @property def A_ ( self : Dict ) -> int: """simple docstring""" return math.prod(self.conv_stride )
663
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" @require_torch def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = pipeline( task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused" ) SCREAMING_SNAKE_CASE__ : int = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : int = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> Dict: """simple docstring""" pass @slow @require_torch def A_ ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pipeline( task="zero-shot-audio-classification", model="laion/clap-htsat-unfused", ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ : List[str] = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Optional[Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier( [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5 ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> List[str]: """simple docstring""" pass
663
1
import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging _lowerCamelCase : str = logging.get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any=False ) -> Tuple: '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise if not is_sharded: SCREAMING_SNAKE_CASE__ : int = os.path.abspath(SCREAMING_SNAKE_CASE__ ) logger.info(f'''Loading PyTorch weights from {pt_path}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.load(SCREAMING_SNAKE_CASE__ , map_location="cpu" ) logger.info(f'''PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters.''' ) SCREAMING_SNAKE_CASE__ : List[Any] = convert_pytorch_state_dict_to_flax(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files SCREAMING_SNAKE_CASE__ : Optional[Any] = convert_pytorch_sharded_state_dict_to_flax(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return flax_state_dict def _a ( SCREAMING_SNAKE_CASE__ : Tuple[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, jnp.ndarray] , SCREAMING_SNAKE_CASE__ : str , ) -> (Tuple[str], np.ndarray): '''simple docstring''' def is_key_or_prefix_key_in_dict(SCREAMING_SNAKE_CASE__ : Tuple[str] ) -> bool: return len(set(SCREAMING_SNAKE_CASE__ ) & {key, (model_prefix,) + key} ) > 0 # layer norm SCREAMING_SNAKE_CASE__ : Dict = pt_tuple_key[:-1] + ("scale",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(SCREAMING_SNAKE_CASE__ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean SCREAMING_SNAKE_CASE__ : Any = pt_tuple_key[:-1] + ("mean",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(SCREAMING_SNAKE_CASE__ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var SCREAMING_SNAKE_CASE__ : Union[str, Any] = pt_tuple_key[:-1] + ("var",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(SCREAMING_SNAKE_CASE__ ): return renamed_pt_tuple_key, pt_tensor # embedding SCREAMING_SNAKE_CASE__ : Any = pt_tuple_key[:-1] + ("embedding",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(SCREAMING_SNAKE_CASE__ ): return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : str = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE__ : str = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : int = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE__ : Optional[int] = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): SCREAMING_SNAKE_CASE__ : Any = pt_tuple_key[-2] + "_g" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): SCREAMING_SNAKE_CASE__ : str = pt_tuple_key[-2] + "_v" if name is not None: SCREAMING_SNAKE_CASE__ : Dict = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def _a ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE__ : Optional[Any] = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: SCREAMING_SNAKE_CASE__ : Dict = flax_model.params["params"] else: SCREAMING_SNAKE_CASE__ : Optional[int] = flax_model.params SCREAMING_SNAKE_CASE__ : Optional[int] = flatten_dict(SCREAMING_SNAKE_CASE__ ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE__ : Any = flatten_dict(flax_model.params["batch_stats"] ) random_flax_state_dict.update(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = {} SCREAMING_SNAKE_CASE__ : Tuple = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE__ : Tuple = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE__ : Tuple = tuple(pt_key.split("." ) ) # remove base model prefix if necessary SCREAMING_SNAKE_CASE__ : Tuple = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Any = rename_key_and_reshape_tensor( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # add model prefix if necessary SCREAMING_SNAKE_CASE__ : Dict = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE__ : int = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ''' f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: SCREAMING_SNAKE_CASE__ : Any = jnp.asarray(SCREAMING_SNAKE_CASE__ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : List[str] = jnp.asarray(SCREAMING_SNAKE_CASE__ ) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : List[Any] = jnp.asarray(SCREAMING_SNAKE_CASE__ ) return unflatten_dict(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> int: '''simple docstring''' import torch # Load the index SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} for shard_file in shard_filenames: # load using msgpack utils SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.load(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE__ : List[Any] = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE__ : List[str] = flax_model.params["params"] SCREAMING_SNAKE_CASE__ : List[Any] = flatten_dict(SCREAMING_SNAKE_CASE__ ) random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"] ) ) else: SCREAMING_SNAKE_CASE__ : Any = flax_model.params SCREAMING_SNAKE_CASE__ : List[str] = flatten_dict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE__ : List[str] = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE__ : str = tuple(pt_key.split("." ) ) # remove base model prefix if necessary SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = rename_key_and_reshape_tensor( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # add model prefix if necessary SCREAMING_SNAKE_CASE__ : Optional[int] = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE__ : List[Any] = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ''' f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: SCREAMING_SNAKE_CASE__ : str = jnp.asarray(SCREAMING_SNAKE_CASE__ ) continue if "var" in flax_key[-1]: SCREAMING_SNAKE_CASE__ : Tuple = jnp.asarray(SCREAMING_SNAKE_CASE__ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : Tuple = jnp.asarray(SCREAMING_SNAKE_CASE__ ) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : str = jnp.asarray(SCREAMING_SNAKE_CASE__ ) return unflatten_dict(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = os.path.abspath(SCREAMING_SNAKE_CASE__ ) logger.info(f'''Loading Flax weights from {flax_checkpoint_path}''' ) # import correct flax class SCREAMING_SNAKE_CASE__ : List[str] = getattr(SCREAMING_SNAKE_CASE__ , "Flax" + model.__class__.__name__ ) # load flax weight dict with open(SCREAMING_SNAKE_CASE__ , "rb" ) as state_f: try: SCREAMING_SNAKE_CASE__ : Optional[Any] = from_bytes(SCREAMING_SNAKE_CASE__ , state_f.read() ) except UnpicklingError: raise EnvironmentError(f'''Unable to convert {flax_checkpoint_path} to Flax deserializable object. ''' ) return load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( "Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE__ : Any = flatten_dict(jax.tree_util.tree_map(lambda SCREAMING_SNAKE_CASE__ : x.dtype == jnp.bfloataa , SCREAMING_SNAKE_CASE__ ) ).values() if any(SCREAMING_SNAKE_CASE__ ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) SCREAMING_SNAKE_CASE__ : Dict = jax.tree_util.tree_map( lambda SCREAMING_SNAKE_CASE__ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = flatten_dict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pt_model.state_dict() SCREAMING_SNAKE_CASE__ : Union[str, Any] = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split("." )[0] for k in pt_model_dict.keys()} ) SCREAMING_SNAKE_CASE__ : Any = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split("." )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[Any] = flax_key_tuple[0] == pt_model.base_model_prefix SCREAMING_SNAKE_CASE__ : Dict = ".".join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE__ : Union[str, Any] = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(SCREAMING_SNAKE_CASE__ ) not in pt_model_dict: # conv layer SCREAMING_SNAKE_CASE__ : int = flax_key_tuple[:-1] + ("weight",) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.transpose(SCREAMING_SNAKE_CASE__ , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(SCREAMING_SNAKE_CASE__ ) not in pt_model_dict: # linear layer SCREAMING_SNAKE_CASE__ : int = flax_key_tuple[:-1] + ("weight",) SCREAMING_SNAKE_CASE__ : Dict = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: SCREAMING_SNAKE_CASE__ : str = flax_key_tuple[:-1] + ("weight",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = flax_key_tuple[:-1] + ("running_mean",) elif "var" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE__ : str = flax_key_tuple[:-1] + ("running_var",) if "batch_stats" in flax_state: SCREAMING_SNAKE_CASE__ : List[str] = ".".join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: SCREAMING_SNAKE_CASE__ : Any = ".".join(SCREAMING_SNAKE_CASE__ ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. SCREAMING_SNAKE_CASE__ : List[str] = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: SCREAMING_SNAKE_CASE__ : Dict = key.split("." ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if key_components[-3::2] == ["parametrizations", "original0"]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = key_components[-2] + "_g" elif key_components[-3::2] == ["parametrizations", "original1"]: SCREAMING_SNAKE_CASE__ : str = key_components[-2] + "_v" if name is not None: SCREAMING_SNAKE_CASE__ : List[Any] = key_components[:-3] + [name] SCREAMING_SNAKE_CASE__ : str = ".".join(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = key if flax_key in special_pt_names: SCREAMING_SNAKE_CASE__ : str = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'''Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ''' f'''to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE__ : List[Any] = np.asarray(SCREAMING_SNAKE_CASE__ ) if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE__ : Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) # remove from missing keys missing_keys.remove(SCREAMING_SNAKE_CASE__ ) else: # weight is not expected by PyTorch model unexpected_keys.append(SCREAMING_SNAKE_CASE__ ) pt_model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE__ : Dict = list(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" f''' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing''' f''' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture''' " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" f''' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect''' " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) else: logger.warning(f'''All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n''' ) if len(SCREAMING_SNAKE_CASE__ ) > 0: logger.warning( f'''Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly''' f''' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to''' " use it for predictions and inference." ) else: logger.warning( f'''All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n''' "If your task is similar to the task the model of the checkpoint was trained on, " f'''you can already use {pt_model.__class__.__name__} for predictions without further training.''' ) return pt_model
663
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase : List[str] = 2_0_0 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase : Any = 5_0 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase : str = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1_0_0_0)) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, float]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = len([g for position, g in enumerate(SCREAMING_SNAKE_CASE__ ) if g == main_target[position]] ) return (item, float(SCREAMING_SNAKE_CASE__ )) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) SCREAMING_SNAKE_CASE__ : Tuple = parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE__ : str = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = list(SCREAMING_SNAKE_CASE__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE__ : Tuple = random.choice(SCREAMING_SNAKE_CASE__ ) return "".join(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : tuple[str, float] , SCREAMING_SNAKE_CASE__ : list[tuple[str, float]] , SCREAMING_SNAKE_CASE__ : list[str] , ) -> list[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE__ : List[str] = int(parent_a[1] * 1_00 ) + 1 SCREAMING_SNAKE_CASE__ : Tuple = 10 if child_n >= 10 else child_n for _ in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = population_score[random.randint(0 , SCREAMING_SNAKE_CASE__ )][0] SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = crossover(parent_a[0] , SCREAMING_SNAKE_CASE__ ) # Append new string to the population list. pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) return pop def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] , SCREAMING_SNAKE_CASE__ : bool = True ) -> tuple[int, int, str]: '''simple docstring''' if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE__ : str = f'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE__ : Optional[int] = sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE__ : Dict = f'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Generate random starting population. SCREAMING_SNAKE_CASE__ : List[Any] = [] for _ in range(SCREAMING_SNAKE_CASE__ ): population.append("".join([random.choice(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(SCREAMING_SNAKE_CASE__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE__ : int = [evaluate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE__ : List[str] = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[1] , reverse=SCREAMING_SNAKE_CASE__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f'''\nGeneration: {generation}''' f'''\nTotal Population:{total_population}''' f'''\nBest score: {population_score[0][1]}''' f'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE__ : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(SCREAMING_SNAKE_CASE__ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ (item, score / len(SCREAMING_SNAKE_CASE__ )) for item, score in population_score ] # This is selection for i in range(SCREAMING_SNAKE_CASE__ ): population.extend(select(population_score[int(SCREAMING_SNAKE_CASE__ )] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(SCREAMING_SNAKE_CASE__ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase : Dict = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) _lowerCamelCase : Tuple = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = basic(target_str, genes_list) print( f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
663
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : List[str] = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[str] = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[str] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys _lowerCamelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
from collections.abc import Callable import numpy as np def _a ( SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = int(np.ceil((x_end - xa) / step_size ) ) SCREAMING_SNAKE_CASE__ : Tuple = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE__ : Tuple = ya SCREAMING_SNAKE_CASE__ : Dict = xa for k in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = y[k] + step_size * ode_func(SCREAMING_SNAKE_CASE__ , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
663
1
_lowerCamelCase : Any = { '''a''': '''AAAAA''', '''b''': '''AAAAB''', '''c''': '''AAABA''', '''d''': '''AAABB''', '''e''': '''AABAA''', '''f''': '''AABAB''', '''g''': '''AABBA''', '''h''': '''AABBB''', '''i''': '''ABAAA''', '''j''': '''BBBAA''', '''k''': '''ABAAB''', '''l''': '''ABABA''', '''m''': '''ABABB''', '''n''': '''ABBAA''', '''o''': '''ABBAB''', '''p''': '''ABBBA''', '''q''': '''ABBBB''', '''r''': '''BAAAA''', '''s''': '''BAAAB''', '''t''': '''BAABA''', '''u''': '''BAABB''', '''v''': '''BBBAB''', '''w''': '''BABAA''', '''x''': '''BABAB''', '''y''': '''BABBA''', '''z''': '''BABBB''', ''' ''': ''' ''', } _lowerCamelCase : Optional[Any] = {value: key for key, value in encode_dict.items()} def _a ( SCREAMING_SNAKE_CASE__ : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces" ) return encoded def _a ( SCREAMING_SNAKE_CASE__ : str ) -> str: '''simple docstring''' if set(SCREAMING_SNAKE_CASE__ ) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces" ) SCREAMING_SNAKE_CASE__ : Optional[int] = "" for word in coded.split(): while len(SCREAMING_SNAKE_CASE__ ) != 0: decoded += decode_dict[word[:5]] SCREAMING_SNAKE_CASE__ : Optional[int] = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
663
def _a ( SCREAMING_SNAKE_CASE__ : List[Any]=2_81_23 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i SCREAMING_SNAKE_CASE__ : int = set() SCREAMING_SNAKE_CASE__ : Any = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(SCREAMING_SNAKE_CASE__ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
663
1
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time _lowerCamelCase : int = Lock() def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[int]: '''simple docstring''' global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(SCREAMING_SNAKE_CASE__ ) process_lock.release() # receive your right neighbor's value process_lock.acquire() SCREAMING_SNAKE_CASE__ : Tuple = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left SCREAMING_SNAKE_CASE__ : Optional[Any] = min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(SCREAMING_SNAKE_CASE__ ) process_lock.release() # receive your left neighbor's value process_lock.acquire() SCREAMING_SNAKE_CASE__ : Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right SCREAMING_SNAKE_CASE__ : Optional[int] = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # after all swaps are performed, send the values back to main result_pipe[1].send(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : str = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop SCREAMING_SNAKE_CASE__ : Tuple = Pipe() SCREAMING_SNAKE_CASE__ : str = Pipe() process_array_.append( Process( target=SCREAMING_SNAKE_CASE__ , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) SCREAMING_SNAKE_CASE__ : int = temp_rs SCREAMING_SNAKE_CASE__ : str = temp_rr for i in range(1 , len(SCREAMING_SNAKE_CASE__ ) - 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = Pipe() SCREAMING_SNAKE_CASE__ : int = Pipe() process_array_.append( Process( target=SCREAMING_SNAKE_CASE__ , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) SCREAMING_SNAKE_CASE__ : List[Any] = temp_rs SCREAMING_SNAKE_CASE__ : List[str] = temp_rr process_array_.append( Process( target=SCREAMING_SNAKE_CASE__ , args=( len(SCREAMING_SNAKE_CASE__ ) - 1, arr[len(SCREAMING_SNAKE_CASE__ ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(SCREAMING_SNAKE_CASE__ ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(SCREAMING_SNAKE_CASE__ ) ): SCREAMING_SNAKE_CASE__ : Tuple = result_pipe[p][0].recv() process_array_[p].join() return arr def _a ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = list(range(10 , 0 , -1 ) ) print("Initial List" ) print(*SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[str] = odd_even_transposition(SCREAMING_SNAKE_CASE__ ) print("Sorted List\n" ) print(*SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
663
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase : Optional[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = ['''MobileViTFeatureExtractor'''] _lowerCamelCase : List[str] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[Any] = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = KandinskyVaaPriorPipeline UpperCAmelCase_ = ["prompt"] UpperCAmelCase_ = ["prompt", "negative_prompt"] UpperCAmelCase_ = [ "num_images_per_prompt", "generator", "num_inference_steps", "latents", "negative_prompt", "guidance_scale", "output_type", "return_dict", ] UpperCAmelCase_ = False @property def A_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" return 3_2 @property def A_ ( self : List[Any] ) -> str: """simple docstring""" return 3_2 @property def A_ ( self : str ) -> Optional[int]: """simple docstring""" return self.time_input_dim @property def A_ ( self : Any ) -> Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> int: """simple docstring""" return 1_0_0 @property def A_ ( self : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def A_ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=self.text_embedder_hidden_size, projection_dim=self.text_embedder_hidden_size, intermediate_size=3_7, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, ) return CLIPTextModelWithProjection(_UpperCAmelCase ) @property def A_ ( self : Any ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = { "num_attention_heads": 2, "attention_head_dim": 1_2, "embedding_dim": self.text_embedder_hidden_size, "num_layers": 1, } SCREAMING_SNAKE_CASE__ : Any = PriorTransformer(**_UpperCAmelCase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 SCREAMING_SNAKE_CASE__ : int = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size, image_size=2_2_4, projection_dim=self.text_embedder_hidden_size, intermediate_size=3_7, num_attention_heads=4, num_channels=3, num_hidden_layers=5, patch_size=1_4, ) SCREAMING_SNAKE_CASE__ : List[str] = CLIPVisionModelWithProjection(_UpperCAmelCase ) return model @property def A_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = CLIPImageProcessor( crop_size=2_2_4, do_center_crop=_UpperCAmelCase, do_normalize=_UpperCAmelCase, do_resize=_UpperCAmelCase, image_mean=[0.48145466, 0.4578275, 0.40821073], image_std=[0.26862954, 0.26130258, 0.27577711], resample=3, size=2_2_4, ) return image_processor def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_prior SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_image_encoder SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ : int = self.dummy_image_processor SCREAMING_SNAKE_CASE__ : Dict = UnCLIPScheduler( variance_type="fixed_small_log", prediction_type="sample", num_train_timesteps=1_0_0_0, clip_sample=_UpperCAmelCase, clip_sample_range=10.0, ) SCREAMING_SNAKE_CASE__ : Any = { "prior": prior, "image_encoder": image_encoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "scheduler": scheduler, "image_processor": image_processor, } return components def A_ ( self : Optional[int], _UpperCAmelCase : int, _UpperCAmelCase : Optional[Any]=0 ) -> Optional[int]: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : int = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = { "prompt": "horse", "generator": generator, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def A_ ( self : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = "cpu" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : str = self.pipeline_class(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = pipe(**self.get_dummy_inputs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[str] = output.image_embeds SCREAMING_SNAKE_CASE__ : int = pipe( **self.get_dummy_inputs(_UpperCAmelCase ), return_dict=_UpperCAmelCase, )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -1_0:] SCREAMING_SNAKE_CASE__ : int = image_from_tuple[0, -1_0:] assert image.shape == (1, 3_2) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def A_ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch_device == "cpu" SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : List[str] = False self._test_inference_batch_single_identical( test_max_difference=_UpperCAmelCase, relax_max_difference=_UpperCAmelCase, test_mean_pixel_difference=_UpperCAmelCase, ) @skip_mps def A_ ( self : str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = torch_device == "cpu" SCREAMING_SNAKE_CASE__ : Optional[int] = False self._test_attention_slicing_forward_pass( test_max_difference=_UpperCAmelCase, test_mean_pixel_difference=_UpperCAmelCase, )
663
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = BlenderbotSmallConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Optional[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : Optional[int]=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : List[Any]=True, _UpperCAmelCase : Union[str, Any]=False, _UpperCAmelCase : str=9_9, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Any=2, _UpperCAmelCase : Any=4, _UpperCAmelCase : List[Any]=3_7, _UpperCAmelCase : Dict=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=2_0, _UpperCAmelCase : int=2, _UpperCAmelCase : Union[str, Any]=1, _UpperCAmelCase : List[str]=0, ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = eos_token_id SCREAMING_SNAKE_CASE__ : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE__ : List[Any] = bos_token_id def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Dict = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Any = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : str = prepare_blenderbot_small_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFBlenderbotSmallModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Optional[Any] = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : List[str] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : Tuple = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Dict = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : int = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Any = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Tuple = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : Tuple = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) UpperCAmelCase_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFBlenderbotSmallForConditionalGeneration, "feature-extraction": TFBlenderbotSmallModel, "summarization": TFBlenderbotSmallForConditionalGeneration, "text2text-generation": TFBlenderbotSmallForConditionalGeneration, "translation": TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFBlenderbotSmallModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[int] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Any ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like " " i'm going to throw up.\nand why is that?" ] UpperCAmelCase_ = "facebook/blenderbot_small-90M" @cached_property def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def A_ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
663
1
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase : """simple docstring""" def __init__( self : str, _UpperCAmelCase : Optional[int], _UpperCAmelCase : Union[str, Any]=1_3, _UpperCAmelCase : str=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Union[str, Any]=3, _UpperCAmelCase : int=1_6, _UpperCAmelCase : Dict=[3_2, 6_4, 1_2_8], _UpperCAmelCase : Optional[int]=[1, 2, 1], _UpperCAmelCase : Optional[int]=[2, 2, 4], _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Optional[int]=2.0, _UpperCAmelCase : List[str]=True, _UpperCAmelCase : Dict=0.0, _UpperCAmelCase : Optional[Any]=0.0, _UpperCAmelCase : Union[str, Any]=0.1, _UpperCAmelCase : List[str]="gelu", _UpperCAmelCase : str=False, _UpperCAmelCase : List[str]=True, _UpperCAmelCase : Union[str, Any]=0.02, _UpperCAmelCase : str=1E-5, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Union[str, Any]=None, _UpperCAmelCase : Tuple=True, _UpperCAmelCase : str=1_0, _UpperCAmelCase : str=8, _UpperCAmelCase : Any=["stage1", "stage2"], _UpperCAmelCase : Dict=[1, 2], ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = parent SCREAMING_SNAKE_CASE__ : List[str] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = image_size SCREAMING_SNAKE_CASE__ : Any = patch_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : int = embed_dim SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Dict = depths SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = window_size SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Dict = qkv_bias SCREAMING_SNAKE_CASE__ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : str = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = patch_norm SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = encoder_stride SCREAMING_SNAKE_CASE__ : Optional[int] = out_features SCREAMING_SNAKE_CASE__ : List[str] = out_indices def A_ ( self : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" return FocalNetConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, hidden_sizes=self.hidden_sizes, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, out_features=self.out_features, out_indices=self.out_indices, ) def A_ ( self : Optional[int], _UpperCAmelCase : Dict, _UpperCAmelCase : str, _UpperCAmelCase : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FocalNetModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE__ : Dict = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def A_ ( self : str, _UpperCAmelCase : Any, _UpperCAmelCase : Optional[Any], _UpperCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FocalNetBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ), len(config.out_features ) ) self.parent.assertListEqual(model.channels, config.hidden_sizes[:-1] ) # verify backbone works with out_features=None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = FocalNetBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ), 1 ) self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]] ) def A_ ( self : Dict, _UpperCAmelCase : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FocalNetForMaskedImageModeling(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(_UpperCAmelCase ) self.parent.assertEqual( result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : Tuple = FocalNetForMaskedImageModeling(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[str] = model(_UpperCAmelCase ) self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size) ) def A_ ( self : Dict, _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] = FocalNetForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(_UpperCAmelCase, labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : Dict = FocalNetForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def A_ ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) UpperCAmelCase_ = ( {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification} if is_torch_available() else {} ) UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FocalNetModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self, config_class=_UpperCAmelCase, embed_dim=3_7, has_text_modality=_UpperCAmelCase ) def A_ ( self : List[Any] ) -> Optional[int]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" return def A_ ( self : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @unittest.skip(reason="FocalNet does not use inputs_embeds" ) def A_ ( self : int ) -> Dict: """simple docstring""" pass @unittest.skip(reason="FocalNet does not use feedforward chunking" ) def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" pass def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) SCREAMING_SNAKE_CASE__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, nn.Linear ) ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : int = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) def A_ ( self : Optional[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : Any, _UpperCAmelCase : Any, _UpperCAmelCase : str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(**self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Tuple = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[int] = getattr( self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_UpperCAmelCase ), _UpperCAmelCase ) # FocalNet has a different seq_length SCREAMING_SNAKE_CASE__ : Any = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) SCREAMING_SNAKE_CASE__ : Dict = outputs.reshaped_hidden_states self.assertEqual(len(_UpperCAmelCase ), _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = reshaped_hidden_states[0].shape SCREAMING_SNAKE_CASE__ : Optional[int] = ( reshaped_hidden_states[0].view(_UpperCAmelCase, _UpperCAmelCase, height * width ).permute(0, 2, 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE__ : Tuple = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : str = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Any = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE__ : List[Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Any = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) @slow def A_ ( self : Tuple ) -> Optional[int]: """simple docstring""" for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = FocalNetModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def A_ ( self : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = _config_zero_init(_UpperCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(config=_UpperCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item(), [0.0, 1.0], msg=F'''Parameter {name} of model {model_class} seems not properly initialized''', ) @require_vision @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" @cached_property def A_ ( self : Dict ) -> Tuple: """simple docstring""" # TODO update organization return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny" ) if is_vision_available() else None @slow def A_ ( self : List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny" ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE__ : Dict = image_processor(images=_UpperCAmelCase, return_tensors="pt" ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**_UpperCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE__ : Tuple = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([0.2166, -0.4368, 0.2191] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3], _UpperCAmelCase, atol=1E-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item(), 2_8_1 ) @require_torch class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (FocalNetBackbone,) if is_torch_available() else () UpperCAmelCase_ = FocalNetConfig UpperCAmelCase_ = False def A_ ( self : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FocalNetModelTester(self )
663
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (DPMSolverSDEScheduler,) UpperCAmelCase_ = 10 def A_ ( self : List[str], **_UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "noise_sampler_seed": 0, } config.update(**_UpperCAmelCase ) return config def A_ ( self : Tuple ) -> int: """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_UpperCAmelCase ) def A_ ( self : int ) -> int: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001], [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_UpperCAmelCase, beta_end=_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : int = self.dummy_model() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Union[str, Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Dict = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config(prediction_type="v_prediction" ) SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Tuple = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def A_ ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : int = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Tuple = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Any = scheduler_class(**_UpperCAmelCase, use_karras_sigmas=_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : str = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
663
1
import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib _lowerCamelCase : List[str] = threading.Lock() _lowerCamelCase : Optional[logging.Handler] = None _lowerCamelCase : Any = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } _lowerCamelCase : List[Any] = logging.WARNING _lowerCamelCase : Union[str, Any] = True def _a ( ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = os.getenv("TRANSFORMERS_VERBOSITY" , SCREAMING_SNAKE_CASE__ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ''' f'''has to be one of: { ", ".join(log_levels.keys() ) }''' ) return _default_log_level def _a ( ) -> str: '''simple docstring''' return __name__.split("." )[0] def _a ( ) -> logging.Logger: '''simple docstring''' return logging.getLogger(_get_library_name() ) def _a ( ) -> None: '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.StreamHandler() # Set sys.stderr as stream. SCREAMING_SNAKE_CASE__ : Optional[Any] = sys.stderr.flush # Apply our default configuration to the library root logger. SCREAMING_SNAKE_CASE__ : Any = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) SCREAMING_SNAKE_CASE__ : Any = False def _a ( ) -> None: '''simple docstring''' global _default_handler with _lock: if not _default_handler: return SCREAMING_SNAKE_CASE__ : List[str] = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) SCREAMING_SNAKE_CASE__ : str = None def _a ( ) -> Any: '''simple docstring''' return log_levels def _a ( SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> logging.Logger: '''simple docstring''' if name is None: SCREAMING_SNAKE_CASE__ : Optional[int] = _get_library_name() _configure_library_root_logger() return logging.getLogger(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> int: '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def _a ( SCREAMING_SNAKE_CASE__ : int ) -> None: '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> List[Any]: '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> Union[str, Any]: '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> Any: '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> Optional[int]: '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> None: '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def _a ( ) -> None: '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def _a ( SCREAMING_SNAKE_CASE__ : logging.Handler ) -> None: '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : logging.Handler ) -> None: '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> None: '''simple docstring''' _configure_library_root_logger() SCREAMING_SNAKE_CASE__ : Dict = False def _a ( ) -> None: '''simple docstring''' _configure_library_root_logger() SCREAMING_SNAKE_CASE__ : List[str] = True def _a ( ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = _get_library_root_logger().handlers for handler in handlers: SCREAMING_SNAKE_CASE__ : Any = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" ) handler.setFormatter(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(SCREAMING_SNAKE_CASE__ ) def _a ( self : List[Any] , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , SCREAMING_SNAKE_CASE__ ) if no_advisory_warnings: return self.warning(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Dict = warning_advice @functools.lru_cache(SCREAMING_SNAKE_CASE__ ) def _a ( self : Dict , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> str: '''simple docstring''' self.warning(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[str] = warning_once class lowerCamelCase : """simple docstring""" def __init__( self : Any, *_UpperCAmelCase : List[str], **_UpperCAmelCase : Any ) -> List[Any]: # pylint: disable=unused-argument """simple docstring""" SCREAMING_SNAKE_CASE__ : int = args[0] if args else None def __iter__( self : List[str] ) -> str: """simple docstring""" return iter(self._iterator ) def __getattr__( self : Union[str, Any], _UpperCAmelCase : Dict ) -> Any: """simple docstring""" def empty_fn(*_UpperCAmelCase : Optional[int], **_UpperCAmelCase : Any ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : int ) -> Union[str, Any]: """simple docstring""" return self def __exit__( self : List[str], _UpperCAmelCase : str, _UpperCAmelCase : Any, _UpperCAmelCase : List[str] ) -> Optional[Any]: """simple docstring""" return class lowerCamelCase : """simple docstring""" def __call__( self : Any, *_UpperCAmelCase : Dict, **_UpperCAmelCase : int ) -> str: """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm(*_UpperCAmelCase, **_UpperCAmelCase ) else: return EmptyTqdm(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Optional[Any], *_UpperCAmelCase : List[Any], **_UpperCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : str ) -> Tuple: """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() _lowerCamelCase : Any = _tqdm_cls() def _a ( ) -> bool: '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def _a ( ) -> List[Any]: '''simple docstring''' global _tqdm_active SCREAMING_SNAKE_CASE__ : Dict = True hf_hub_utils.enable_progress_bars() def _a ( ) -> Union[str, Any]: '''simple docstring''' global _tqdm_active SCREAMING_SNAKE_CASE__ : Optional[Any] = False hf_hub_utils.disable_progress_bars()
663
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = ["image_processor", "tokenizer"] UpperCAmelCase_ = "AutoImageProcessor" UpperCAmelCase_ = "AutoTokenizer" def __init__( self : Tuple, _UpperCAmelCase : str=None, _UpperCAmelCase : str=None, **_UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead.", _UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop("feature_extractor" ) SCREAMING_SNAKE_CASE__ : Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.image_processor SCREAMING_SNAKE_CASE__ : Any = False def __call__( self : List[str], *_UpperCAmelCase : Any, **_UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("images", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = args[0] SCREAMING_SNAKE_CASE__ : str = args[1:] if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: SCREAMING_SNAKE_CASE__ : Dict = self.image_processor(_UpperCAmelCase, *_UpperCAmelCase, **_UpperCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if text is None: return inputs elif images is None: return encodings else: SCREAMING_SNAKE_CASE__ : Optional[int] = encodings["input_ids"] return inputs def A_ ( self : Dict, *_UpperCAmelCase : Tuple, **_UpperCAmelCase : Dict ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : List[str], *_UpperCAmelCase : int, **_UpperCAmelCase : Dict ) -> Any: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) @contextmanager def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your images inputs, or in a separate call." ) SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False def A_ ( self : Tuple, _UpperCAmelCase : List[Any], _UpperCAmelCase : int=False, _UpperCAmelCase : Optional[Any]=None ) -> Any: """simple docstring""" if added_vocab is None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer.get_added_vocab() SCREAMING_SNAKE_CASE__ : str = {} while tokens: SCREAMING_SNAKE_CASE__ : Dict = re.search(r"<s_(.*?)>", _UpperCAmelCase, re.IGNORECASE ) if start_token is None: break SCREAMING_SNAKE_CASE__ : Any = start_token.group(1 ) SCREAMING_SNAKE_CASE__ : Dict = re.search(rF'''</s_{key}>''', _UpperCAmelCase, re.IGNORECASE ) SCREAMING_SNAKE_CASE__ : Any = start_token.group() if end_token is None: SCREAMING_SNAKE_CASE__ : List[str] = tokens.replace(_UpperCAmelCase, "" ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = end_token.group() SCREAMING_SNAKE_CASE__ : List[str] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}''', _UpperCAmelCase, re.IGNORECASE ) if content is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node SCREAMING_SNAKE_CASE__ : str = self.tokenajson(_UpperCAmelCase, is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if value: if len(_UpperCAmelCase ) == 1: SCREAMING_SNAKE_CASE__ : str = value[0] SCREAMING_SNAKE_CASE__ : List[str] = value else: # leaf nodes SCREAMING_SNAKE_CASE__ : Optional[int] = [] for leaf in content.split(r"<sep/>" ): SCREAMING_SNAKE_CASE__ : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": SCREAMING_SNAKE_CASE__ : str = leaf[1:-2] # for categorical special tokens output[key].append(_UpperCAmelCase ) if len(output[key] ) == 1: SCREAMING_SNAKE_CASE__ : str = output[key][0] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokens[tokens.find(_UpperCAmelCase ) + len(_UpperCAmelCase ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if len(_UpperCAmelCase ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def A_ ( self : str ) -> Optional[Any]: """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.", _UpperCAmelCase, ) return self.image_processor_class @property def A_ ( self : int ) -> List[str]: """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.", _UpperCAmelCase, ) return self.image_processor
663
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : int = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json''', } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "gpt_neox_japanese" def __init__( self : List[Any], _UpperCAmelCase : Optional[int]=3_2_0_0_0, _UpperCAmelCase : List[str]=2_5_6_0, _UpperCAmelCase : Optional[Any]=3_2, _UpperCAmelCase : int=3_2, _UpperCAmelCase : Any=4, _UpperCAmelCase : List[str]="gelu", _UpperCAmelCase : List[Any]=1.00, _UpperCAmelCase : Optional[Any]=1_0_0_0_0, _UpperCAmelCase : Tuple=2_0_4_8, _UpperCAmelCase : int=0.02, _UpperCAmelCase : Optional[int]=1E-5, _UpperCAmelCase : List[Any]=True, _UpperCAmelCase : Dict=3_1_9_9_6, _UpperCAmelCase : Optional[int]=3_1_9_9_9, _UpperCAmelCase : str=0.1, _UpperCAmelCase : Tuple=0.0, **_UpperCAmelCase : Optional[int], ) -> int: """simple docstring""" super().__init__(bos_token_id=_UpperCAmelCase, eos_token_id=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_multiple_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = rotary_pct SCREAMING_SNAKE_CASE__ : Optional[int] = rotary_emb_base SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : Optional[int] = use_cache SCREAMING_SNAKE_CASE__ : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _lowerCamelCase : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = ['''BartphoTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[Any] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : str = SamProcessor(_UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) def A_ ( self : List[str], **_UpperCAmelCase : Optional[int] ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname, **_UpperCAmelCase ).image_processor def A_ ( self : Dict ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def A_ ( self : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [np.random.randint(2_5_5, size=(3, 3_0, 4_0_0), dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Optional[int] = [Image.fromarray(np.moveaxis(_UpperCAmelCase, 0, -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_UpperCAmelCase, padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Dict = SamProcessor.from_pretrained(self.tmpdirname, do_normalize=_UpperCAmelCase, padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, _UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_processor(_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Optional[int] = processor(images=_UpperCAmelCase, return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1E-2 ) @require_torch def A_ ( self : Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(image_processor=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = [[1_7_6_4, 2_6_4_6]] SCREAMING_SNAKE_CASE__ : Optional[int] = [[6_8_3, 1_0_2_4]] SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) self.assertEqual(masks[0].shape, (1, 3, 1_7_6_4, 2_6_4_6) ) SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks( _UpperCAmelCase, torch.tensor(_UpperCAmelCase ), torch.tensor(_UpperCAmelCase ) ) self.assertEqual(masks[0].shape, (1, 3, 1_7_6_4, 2_6_4_6) ) # should also work with np SCREAMING_SNAKE_CASE__ : str = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks(_UpperCAmelCase, np.array(_UpperCAmelCase ), np.array(_UpperCAmelCase ) ) self.assertEqual(masks[0].shape, (1, 3, 1_7_6_4, 2_6_4_6) ) SCREAMING_SNAKE_CASE__ : Tuple = [[1, 0], [0, 1]] with self.assertRaises(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : int = processor.post_process_masks(_UpperCAmelCase, np.array(_UpperCAmelCase ), np.array(_UpperCAmelCase ) ) @require_vision @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : List[Any] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(_UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) def A_ ( self : Dict, **_UpperCAmelCase : Optional[Any] ) -> Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname, **_UpperCAmelCase ).image_processor def A_ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def A_ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [np.random.randint(2_5_5, size=(3, 3_0, 4_0_0), dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_UpperCAmelCase, 0, -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_image_processor(do_normalize=_UpperCAmelCase, padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Any = SamProcessor.from_pretrained(self.tmpdirname, do_normalize=_UpperCAmelCase, padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, _UpperCAmelCase ) def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(image_processor=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_processor(_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : int = processor(images=_UpperCAmelCase, return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1E-2 ) @require_tf def A_ ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Any = [[1_7_6_4, 2_6_4_6]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[6_8_3, 1_0_2_4]] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, return_tensors="tf" ) self.assertEqual(masks[0].shape, (1, 3, 1_7_6_4, 2_6_4_6) ) SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks( _UpperCAmelCase, tf.convert_to_tensor(_UpperCAmelCase ), tf.convert_to_tensor(_UpperCAmelCase ), return_tensors="tf", ) self.assertEqual(masks[0].shape, (1, 3, 1_7_6_4, 2_6_4_6) ) # should also work with np SCREAMING_SNAKE_CASE__ : Union[str, Any] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks( _UpperCAmelCase, np.array(_UpperCAmelCase ), np.array(_UpperCAmelCase ), return_tensors="tf" ) self.assertEqual(masks[0].shape, (1, 3, 1_7_6_4, 2_6_4_6) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _UpperCAmelCase, np.array(_UpperCAmelCase ), np.array(_UpperCAmelCase ), return_tensors="tf" ) @require_vision @require_torchvision class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : str = SamImageProcessor() SCREAMING_SNAKE_CASE__ : str = SamProcessor(_UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) def A_ ( self : Tuple, **_UpperCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname, **_UpperCAmelCase ).image_processor def A_ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [np.random.randint(2_5_5, size=(3, 3_0, 4_0_0), dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : int = [Image.fromarray(np.moveaxis(_UpperCAmelCase, 0, -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def A_ ( self : List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(image_processor=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = np.random.randint(0, 2, size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : Dict = [tf.convert_to_tensor(_UpperCAmelCase )] SCREAMING_SNAKE_CASE__ : List[str] = [torch.tensor(_UpperCAmelCase )] SCREAMING_SNAKE_CASE__ : List[str] = [[1_7_6_4, 2_6_4_6]] SCREAMING_SNAKE_CASE__ : Dict = [[6_8_3, 1_0_2_4]] SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processor.post_process_masks( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def A_ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(image_processor=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Tuple = image_processor(_UpperCAmelCase, return_tensors="pt" )["pixel_values"].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_UpperCAmelCase, return_tensors="pt" )["pixel_values"].numpy() SCREAMING_SNAKE_CASE__ : Dict = image_processor(_UpperCAmelCase, return_tensors="tf" )["pixel_values"].numpy() SCREAMING_SNAKE_CASE__ : Optional[int] = processor(images=_UpperCAmelCase, return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(_UpperCAmelCase, _UpperCAmelCase ) ) self.assertTrue(np.allclose(_UpperCAmelCase, _UpperCAmelCase ) ) self.assertTrue(np.allclose(_UpperCAmelCase, _UpperCAmelCase ) )
663
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class lowerCamelCase : """simple docstring""" def __init__( self : Any, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Union[str, Any]=1_3, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : str=1_6, _UpperCAmelCase : Tuple=[1, 2, 1], _UpperCAmelCase : List[str]=[2, 2, 4], _UpperCAmelCase : Tuple=2, _UpperCAmelCase : str=2.0, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=0.0, _UpperCAmelCase : Any=0.0, _UpperCAmelCase : Optional[int]=0.1, _UpperCAmelCase : int="gelu", _UpperCAmelCase : Any=False, _UpperCAmelCase : Any=True, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Any=1E-5, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : List[Any]=None, _UpperCAmelCase : str=True, _UpperCAmelCase : Union[str, Any]=1_0, _UpperCAmelCase : List[str]=8, _UpperCAmelCase : Union[str, Any]=["stage1", "stage2", "stage3"], _UpperCAmelCase : Any=[1, 2, 3], ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = embed_dim SCREAMING_SNAKE_CASE__ : List[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = num_heads SCREAMING_SNAKE_CASE__ : str = window_size SCREAMING_SNAKE_CASE__ : Any = mlp_ratio SCREAMING_SNAKE_CASE__ : List[str] = qkv_bias SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = drop_path_rate SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Tuple = patch_norm SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : Optional[int] = use_labels SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_stride SCREAMING_SNAKE_CASE__ : List[Any] = out_features SCREAMING_SNAKE_CASE__ : Dict = out_indices def A_ ( self : List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[int] ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, out_features=self.out_features, out_indices=self.out_indices, ) def A_ ( self : Dict, _UpperCAmelCase : int, _UpperCAmelCase : str, _UpperCAmelCase : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def A_ ( self : Optional[int], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any, _UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = MaskFormerSwinBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ), len(config.out_features ) ) self.parent.assertListEqual(model.channels, [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = ["stem"] SCREAMING_SNAKE_CASE__ : str = MaskFormerSwinBackbone(config=_UpperCAmelCase ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) UpperCAmelCase_ = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = MaskFormerSwinModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = ConfigTester(self, config_class=_UpperCAmelCase, embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def A_ ( self : Any ) -> List[Any]: """simple docstring""" pass def A_ ( self : Tuple ) -> Any: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A_ ( self : int ) -> Optional[Any]: """simple docstring""" return def A_ ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_UpperCAmelCase ) @unittest.skip("Swin does not use inputs_embeds" ) def A_ ( self : Any ) -> Optional[int]: """simple docstring""" pass @unittest.skip("Swin does not support feedforward chunking" ) def A_ ( self : List[str] ) -> Optional[int]: """simple docstring""" pass def A_ ( self : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, nn.Linear ) ) def A_ ( self : Union[str, Any] ) -> List[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__ : Dict = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def A_ ( self : Dict ) -> List[str]: """simple docstring""" pass def A_ ( self : List[str], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr( self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_UpperCAmelCase ), _UpperCAmelCase ) # Swin has a different seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Dict = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Any = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def A_ ( self : List[Any] ) -> Dict: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Dict ) -> str: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" pass def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_UpperCAmelCase : Optional[Any] ): SCREAMING_SNAKE_CASE__ : Dict = 0 return t def check_equivalence(_UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : Optional[Any]={} ): with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ).to_tuple() def recursive_check(_UpperCAmelCase : int, _UpperCAmelCase : Dict ): if isinstance(_UpperCAmelCase, (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_UpperCAmelCase, _UpperCAmelCase ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif isinstance(_UpperCAmelCase, _UpperCAmelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values(), dict_object.values() ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_UpperCAmelCase ), set_nan_tensor_to_zero(_UpperCAmelCase ), atol=1E-5 ), msg=( "Tuple and dict output are not equal. Difference:" F''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' F''' {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}. Dict has''' F''' `nan`: {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}.''' ), ) recursive_check(_UpperCAmelCase, _UpperCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) @require_torch class lowerCamelCase (unittest.TestCase , __lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (MaskFormerSwinBackbone,) if is_torch_available() else () UpperCAmelCase_ = MaskFormerSwinConfig def A_ ( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModelTester(self ) def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = backbone_class(_UpperCAmelCase ) backbone.to(_UpperCAmelCase ) backbone.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps, _UpperCAmelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels ): self.assertTrue(feature_map.shape[:2], (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase, output_hidden_states=_UpperCAmelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ), len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:], backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels), (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: SCREAMING_SNAKE_CASE__ : int = backbone(**_UpperCAmelCase, output_attentions=_UpperCAmelCase ) self.assertIsNotNone(outputs.attentions )
663
1
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position _lowerCamelCase : str = '''2.13.1''' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('''3.7'''): raise ImportWarning( '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.''' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n''' '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.''' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip _lowerCamelCase : Optional[Any] = concatenate_datasets _lowerCamelCase : Dict = DownloadConfig _lowerCamelCase : Union[str, Any] = DownloadManager _lowerCamelCase : Dict = DownloadMode _lowerCamelCase : Any = DownloadConfig _lowerCamelCase : Tuple = DownloadMode _lowerCamelCase : List[Any] = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
663
from ....configuration_utils import PretrainedConfig from ....utils import logging _lowerCamelCase : Any = logging.get_logger(__name__) # TODO: upload to AWS _lowerCamelCase : str = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json''' ), } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "retribert" def __init__( self : Optional[Any], _UpperCAmelCase : Dict=3_0_5_2_2, _UpperCAmelCase : List[str]=7_6_8, _UpperCAmelCase : Tuple=8, _UpperCAmelCase : Optional[Any]=1_2, _UpperCAmelCase : Union[str, Any]=3_0_7_2, _UpperCAmelCase : Dict="gelu", _UpperCAmelCase : Tuple=0.1, _UpperCAmelCase : str=0.1, _UpperCAmelCase : List[str]=5_1_2, _UpperCAmelCase : Optional[int]=2, _UpperCAmelCase : Dict=0.02, _UpperCAmelCase : Any=1E-12, _UpperCAmelCase : Dict=True, _UpperCAmelCase : Any=1_2_8, _UpperCAmelCase : int=0, **_UpperCAmelCase : List[str], ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = share_encoders SCREAMING_SNAKE_CASE__ : int = projection_dim
663
1
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Any ) -> List[str]: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def A_ ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE__ : List[str] = 3 SCREAMING_SNAKE_CASE__ : Union[str, Any] = (3_2, 3_2) SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor((batch_size, num_channels) + sizes, rng=random.Random(0 ) ).to(_UpperCAmelCase ) return image @property def A_ ( self : Any ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = UNetaDConditionModel( block_out_channels=(3_2, 6_4), layers_per_block=2, sample_size=3_2, in_channels=4, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=3_2, ) return model @property def A_ ( self : List[str] ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = AutoencoderKL( block_out_channels=[3_2, 6_4], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, ) return model @property def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=3_2, intermediate_size=3_7, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, ) return CLIPTextModel(_UpperCAmelCase ) @property def A_ ( self : Dict ) -> int: """simple docstring""" def extract(*_UpperCAmelCase : Optional[Any], **_UpperCAmelCase : str ): class lowerCamelCase : """simple docstring""" def __init__( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.ones([0] ) def A_ ( self : Optional[Any], _UpperCAmelCase : Union[str, Any] ) -> str: """simple docstring""" self.pixel_values.to(_UpperCAmelCase ) return self return Out() return extract def A_ ( self : Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ : Optional[int] = DDIMScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=_UpperCAmelCase, set_alpha_to_one=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_vae SCREAMING_SNAKE_CASE__ : Dict = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : List[str] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionPipeline( unet=_UpperCAmelCase, scheduler=_UpperCAmelCase, vae=_UpperCAmelCase, text_encoder=_UpperCAmelCase, tokenizer=_UpperCAmelCase, safety_checker=_UpperCAmelCase, feature_extractor=self.dummy_extractor, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe([prompt], generator=_UpperCAmelCase, guidance_scale=6.0, num_inference_steps=2, output_type="np" ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : List[Any] = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=6.0, num_inference_steps=2, output_type="np", return_dict=_UpperCAmelCase, )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def A_ ( self : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Any = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ : str = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_vae SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : int = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionPipeline( unet=_UpperCAmelCase, scheduler=_UpperCAmelCase, vae=_UpperCAmelCase, text_encoder=_UpperCAmelCase, tokenizer=_UpperCAmelCase, safety_checker=_UpperCAmelCase, feature_extractor=self.dummy_extractor, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE__ : int = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = sd_pipe([prompt], generator=_UpperCAmelCase, guidance_scale=6.0, num_inference_steps=2, output_type="np" ) SCREAMING_SNAKE_CASE__ : Any = output.images SCREAMING_SNAKE_CASE__ : int = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=6.0, num_inference_steps=2, output_type="np", return_dict=_UpperCAmelCase, )[0] SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def A_ ( self : Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe", safety_checker=_UpperCAmelCase ) assert isinstance(_UpperCAmelCase, _UpperCAmelCase ) assert isinstance(pipe.scheduler, _UpperCAmelCase ) assert pipe.safety_checker is None SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe("example prompt", num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) # sanity check that the pipeline still works assert pipe.safety_checker is None SCREAMING_SNAKE_CASE__ : List[str] = pipe("example prompt", num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda", "This test requires a GPU" ) def A_ ( self : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ : Union[str, Any] = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self.dummy_vae SCREAMING_SNAKE_CASE__ : int = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 SCREAMING_SNAKE_CASE__ : Union[str, Any] = unet.half() SCREAMING_SNAKE_CASE__ : List[str] = vae.half() SCREAMING_SNAKE_CASE__ : Dict = bert.half() # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionPipeline( unet=_UpperCAmelCase, scheduler=_UpperCAmelCase, vae=_UpperCAmelCase, text_encoder=_UpperCAmelCase, tokenizer=_UpperCAmelCase, safety_checker=_UpperCAmelCase, feature_extractor=self.dummy_extractor, ) SCREAMING_SNAKE_CASE__ : List[Any] = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE__ : List[Any] = sd_pipe([prompt], num_inference_steps=2, output_type="np" ).images assert image.shape == (1, 6_4, 6_4, 3) @nightly @require_torch_gpu class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Tuple ) -> Union[str, Any]: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : Optional[int] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", safety_checker=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE__ : str = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 4_0_0_3_6_6_0_3_4_6 SCREAMING_SNAKE_CASE__ : Dict = 7 # without safety guidance (sld_guidance_scale = 0) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=_UpperCAmelCase, num_inference_steps=5_0, output_type="np", width=5_1_2, height=5_1_2, sld_guidance_scale=0, ) SCREAMING_SNAKE_CASE__ : Tuple = output.images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=_UpperCAmelCase, num_inference_steps=5_0, output_type="np", width=5_1_2, height=5_1_2, sld_guidance_scale=2_0_0_0, sld_warmup_steps=7, sld_threshold=0.025, sld_momentum_scale=0.5, sld_mom_beta=0.7, ) SCREAMING_SNAKE_CASE__ : Any = output.images SCREAMING_SNAKE_CASE__ : Tuple = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[Any] = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", safety_checker=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = "padme amidala taking a bath artwork, safe for work, no nudity" SCREAMING_SNAKE_CASE__ : Tuple = 2_7_3_4_9_7_1_7_5_5 SCREAMING_SNAKE_CASE__ : Tuple = 7 SCREAMING_SNAKE_CASE__ : Dict = torch.manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=_UpperCAmelCase, num_inference_steps=5_0, output_type="np", width=5_1_2, height=5_1_2, sld_guidance_scale=0, ) SCREAMING_SNAKE_CASE__ : Tuple = output.images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Tuple = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=_UpperCAmelCase, num_inference_steps=5_0, output_type="np", width=5_1_2, height=5_1_2, sld_guidance_scale=2_0_0_0, sld_warmup_steps=7, sld_threshold=0.025, sld_momentum_scale=0.5, sld_mom_beta=0.7, ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[Any] = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) SCREAMING_SNAKE_CASE__ : Dict = 1_0_4_4_3_5_5_2_3_4 SCREAMING_SNAKE_CASE__ : List[str] = 1_2 SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=_UpperCAmelCase, num_inference_steps=5_0, output_type="np", width=5_1_2, height=5_1_2, sld_guidance_scale=0, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 SCREAMING_SNAKE_CASE__ : int = torch.manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe( [prompt], generator=_UpperCAmelCase, guidance_scale=_UpperCAmelCase, num_inference_steps=5_0, output_type="np", width=5_1_2, height=5_1_2, sld_guidance_scale=2_0_0_0, sld_warmup_steps=7, sld_threshold=0.025, sld_momentum_scale=0.5, sld_mom_beta=0.7, ) SCREAMING_SNAKE_CASE__ : List[str] = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
663
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin _lowerCamelCase : int = False @skip_mps class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = StableDiffusionAttendAndExcitePipeline UpperCAmelCase_ = False UpperCAmelCase_ = TEXT_TO_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"} ) UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def A_ ( cls : str ) -> Union[str, Any]: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : Tuple ) -> str: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : Any ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4), layers_per_block=1, sample_size=3_2, in_channels=4, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=3_2, attention_head_dim=(2, 4), use_linear_projection=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=_UpperCAmelCase, set_alpha_to_one=_UpperCAmelCase, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = AutoencoderKL( block_out_channels=[3_2, 6_4], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, sample_size=1_2_8, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=3_2, intermediate_size=3_7, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, hidden_act="gelu", projection_dim=5_1_2, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTextModel(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def A_ ( self : Optional[Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Any=0 ) -> Optional[Any]: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : Tuple = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = { "prompt": "a cat and a frog", "token_indices": [2, 5], "generator": generator, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", "max_iter_to_alter": 2, "thresholds": {0: 0.7}, } return inputs def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = "cpu" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.pipeline_class(**_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_dummy_inputs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = pipe(**_UpperCAmelCase ).images SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 6_4, 6_4, 3) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) SCREAMING_SNAKE_CASE__ : Dict = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_UpperCAmelCase, 1E-3 ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def A_ ( self : Any ) -> str: """simple docstring""" # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : Optional[Any] ) -> str: """simple docstring""" self._test_inference_batch_single_identical(batch_size=2, expected_max_diff=7E-4 ) def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def A_ ( self : Any ) -> List[str]: """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" super().test_save_load_local(expected_max_difference=5E-4 ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class lowerCamelCase (unittest.TestCase ): """simple docstring""" @classmethod def A_ ( cls : Union[str, Any] ) -> Tuple: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : List[str] ) -> List[str]: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(5_1 ) SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionAttendAndExcitePipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=_UpperCAmelCase, torch_dtype=torch.floataa ) pipe.to("cuda" ) SCREAMING_SNAKE_CASE__ : List[str] = "a painting of an elephant with glasses" SCREAMING_SNAKE_CASE__ : Optional[int] = [5, 7] SCREAMING_SNAKE_CASE__ : str = pipe( prompt=_UpperCAmelCase, token_indices=_UpperCAmelCase, guidance_scale=7.5, generator=_UpperCAmelCase, num_inference_steps=5, max_iter_to_alter=5, output_type="numpy", ).images[0] SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy" ) assert np.abs((expected_image - image).max() ) < 5E-1
663
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : str = { '''facebook/data2vec-vision-base-ft''': ( '''https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json''' ), } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "data2vec-vision" def __init__( self : Optional[Any], _UpperCAmelCase : Optional[Any]=7_6_8, _UpperCAmelCase : Optional[Any]=1_2, _UpperCAmelCase : List[Any]=1_2, _UpperCAmelCase : Optional[Any]=3_0_7_2, _UpperCAmelCase : str="gelu", _UpperCAmelCase : List[str]=0.0, _UpperCAmelCase : List[str]=0.0, _UpperCAmelCase : List[str]=0.02, _UpperCAmelCase : List[str]=1E-12, _UpperCAmelCase : List[str]=2_2_4, _UpperCAmelCase : str=1_6, _UpperCAmelCase : List[Any]=3, _UpperCAmelCase : Union[str, Any]=False, _UpperCAmelCase : str=False, _UpperCAmelCase : Optional[Any]=False, _UpperCAmelCase : Optional[int]=False, _UpperCAmelCase : List[Any]=0.1, _UpperCAmelCase : int=0.1, _UpperCAmelCase : Tuple=True, _UpperCAmelCase : Tuple=[3, 5, 7, 1_1], _UpperCAmelCase : List[str]=[1, 2, 3, 6], _UpperCAmelCase : List[str]=True, _UpperCAmelCase : Optional[Any]=0.4, _UpperCAmelCase : Any=2_5_6, _UpperCAmelCase : str=1, _UpperCAmelCase : Dict=False, _UpperCAmelCase : Tuple=2_5_5, **_UpperCAmelCase : Optional[int], ) -> Optional[Any]: """simple docstring""" super().__init__(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = intermediate_size SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : Dict = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[str] = image_size SCREAMING_SNAKE_CASE__ : Optional[Any] = patch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : List[str] = use_mask_token SCREAMING_SNAKE_CASE__ : Dict = use_absolute_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = use_relative_position_bias SCREAMING_SNAKE_CASE__ : List[Any] = use_shared_relative_position_bias SCREAMING_SNAKE_CASE__ : List[str] = layer_scale_init_value SCREAMING_SNAKE_CASE__ : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : Optional[Any] = use_mean_pooling # decode head attributes (semantic segmentation) SCREAMING_SNAKE_CASE__ : str = out_indices SCREAMING_SNAKE_CASE__ : List[Any] = pool_scales # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE__ : str = use_auxiliary_head SCREAMING_SNAKE_CASE__ : str = auxiliary_loss_weight SCREAMING_SNAKE_CASE__ : Optional[Any] = auxiliary_channels SCREAMING_SNAKE_CASE__ : str = auxiliary_num_convs SCREAMING_SNAKE_CASE__ : str = auxiliary_concat_input SCREAMING_SNAKE_CASE__ : Optional[int] = semantic_loss_ignore_index class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = version.parse("1.11" ) @property def A_ ( self : Any ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def A_ ( self : Any ) -> float: """simple docstring""" return 1E-4
663
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = PegasusConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=False, _UpperCAmelCase : Union[str, Any]=9_9, _UpperCAmelCase : Optional[Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=4, _UpperCAmelCase : str=3_7, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=4_0, _UpperCAmelCase : Any=2, _UpperCAmelCase : int=1, _UpperCAmelCase : str=0, ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : str = eos_token_id SCREAMING_SNAKE_CASE__ : Dict = pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = bos_token_id def A_ ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_pegasus_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Union[str, Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFPegasusModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : str = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : int = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : int = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : str = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Optional[Any] = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : List[str]=None , ) -> Any: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase_ = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFPegasusModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_sentencepiece @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] UpperCAmelCase_ = [ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to" " reduce the risk of wildfires.", "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.", ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase_ = "google/pegasus-xsum" @cached_property def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def A_ ( self : str, **_UpperCAmelCase : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.translate_src_text(**_UpperCAmelCase ) assert self.expected_text == generated_words def A_ ( self : Any, **_UpperCAmelCase : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, **_UpperCAmelCase, padding=_UpperCAmelCase, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : List[str] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase ) return generated_words @slow def A_ ( self : List[Any] ) -> Any: """simple docstring""" self._assert_generated_batch_equal_expected()
663
1
from ..utils import DummyObject, requires_backends class lowerCamelCase (metaclass=__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = ["speech"] def __init__( self : List[Any], *_UpperCAmelCase : Dict, **_UpperCAmelCase : List[str] ) -> Dict: """simple docstring""" requires_backends(self, ["speech"] ) class lowerCamelCase (metaclass=__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = ["speech"] def __init__( self : Optional[Any], *_UpperCAmelCase : int, **_UpperCAmelCase : Dict ) -> Tuple: """simple docstring""" requires_backends(self, ["speech"] )
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase : List[str] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = GPTaTokenizer UpperCAmelCase_ = GPTaTokenizerFast UpperCAmelCase_ = True UpperCAmelCase_ = {"add_prefix_space": True} UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : Any = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] SCREAMING_SNAKE_CASE__ : int = dict(zip(_UpperCAmelCase, range(len(_UpperCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE__ : str = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] SCREAMING_SNAKE_CASE__ : Any = {"unk_token": "<unk>"} SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file, "w", encoding="utf-8" ) as fp: fp.write(json.dumps(_UpperCAmelCase ) + "\n" ) with open(self.merges_file, "w", encoding="utf-8" ) as fp: fp.write("\n".join(_UpperCAmelCase ) ) def A_ ( self : Tuple, **_UpperCAmelCase : str ) -> str: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : int, **_UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : Tuple, _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = "lower newer" SCREAMING_SNAKE_CASE__ : List[Any] = "lower newer" return input_text, output_text def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Tuple = "lower newer" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] SCREAMING_SNAKE_CASE__ : Dict = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Dict = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Dict ) -> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = "lower newer" # Testing tokenization SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE__ : Tuple = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing the unknown token SCREAMING_SNAKE_CASE__ : Dict = tokens + [rust_tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : str = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Tuple, *_UpperCAmelCase : List[Any], **_UpperCAmelCase : Union[str, Any] ) -> Optional[int]: """simple docstring""" # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def A_ ( self : Optional[Any], _UpperCAmelCase : int=1_5 ) -> List[str]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Any = self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) # Simple input SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : List[str] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Any = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : List[Any] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) def A_ ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = GPTaTokenizer.from_pretrained(self.tmpdirname, pad_token="<pad>" ) # Simple input SCREAMING_SNAKE_CASE__ : Union[str, Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Dict = ["This is a simple input looooooooong", "This is a simple input"] SCREAMING_SNAKE_CASE__ : List[str] = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : int = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding="max_length", max_length=3_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(*_UpperCAmelCase, padding="max_length", max_length=6_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1], 3_0 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1], 3_3 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1], 6_0 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1], 5_2 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "$$$" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer.from_pretrained(self.tmpdirname, bos_token=_UpperCAmelCase, add_bos_token=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(_UpperCAmelCase ) self.assertEqual(out_s.input_ids[0], _UpperCAmelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.decode(out_s.input_ids ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], _UpperCAmelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def A_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" pass def A_ ( self : Dict ) -> str: """simple docstring""" # TODO: change to self.get_tokenizers() when the fast version is implemented SCREAMING_SNAKE_CASE__ : Any = [self.get_tokenizer(do_lower_case=_UpperCAmelCase, add_bos_token=_UpperCAmelCase )] for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ : List[Any] = "Encode this." SCREAMING_SNAKE_CASE__ : Optional[Any] = "This one too please." SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) encoded_sequence += tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode_plus( _UpperCAmelCase, _UpperCAmelCase, add_special_tokens=_UpperCAmelCase, return_special_tokens_mask=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(_UpperCAmelCase ), len(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(_UpperCAmelCase ) ] SCREAMING_SNAKE_CASE__ : List[Any] = [x for x in filtered_sequence if x is not None] self.assertEqual(_UpperCAmelCase, _UpperCAmelCase ) @require_tokenizers class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Optional[Any] ) -> int: """simple docstring""" # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("test_opt" ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("./test_opt" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", use_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = "A photo of a cat" SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode( _UpperCAmelCase, ) # Same as above self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) @unittest.skip("This test is failing because of a bug in the fast tokenizer" ) def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = "bos" SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.get_vocab()["bos"] SCREAMING_SNAKE_CASE__ : Tuple = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode( _UpperCAmelCase, ) # We changed the bos token self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("./tok" ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained("./tok" ) self.assertTrue(tokenizer.is_fast ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] )
663
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = '''Hello world! cécé herlolip''' def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = FairseqRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) roberta.eval() # disable dropout SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.sentence_encoder SCREAMING_SNAKE_CASE__ : List[str] = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaXLForSequenceClassification(SCREAMING_SNAKE_CASE__ ) if classification_head else XLMRobertaXLForMaskedLM(SCREAMING_SNAKE_CASE__ ) model.eval() # Now let's copy all the weights. # Embeddings SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.embed_tokens.weight SCREAMING_SNAKE_CASE__ : str = roberta_sent_encoder.embed_positions.weight SCREAMING_SNAKE_CASE__ : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. SCREAMING_SNAKE_CASE__ : Any = roberta_sent_encoder.layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer SCREAMING_SNAKE_CASE__ : BertLayer = model.roberta.encoder.layer[i] SCREAMING_SNAKE_CASE__ : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] SCREAMING_SNAKE_CASE__ : RobertaAttention = layer.attention SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn_layer_norm.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn_layer_norm.bias # self attention SCREAMING_SNAKE_CASE__ : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = roberta_layer.self_attn.q_proj.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.self_attn.q_proj.bias SCREAMING_SNAKE_CASE__ : Any = roberta_layer.self_attn.k_proj.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn.k_proj.bias SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.self_attn.v_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.self_attn.v_proj.bias # self-attention output SCREAMING_SNAKE_CASE__ : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.weight SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.bias # this one is final layer norm SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.bias # intermediate SCREAMING_SNAKE_CASE__ : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.bias # output SCREAMING_SNAKE_CASE__ : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.fca.bias # end of layer if classification_head: SCREAMING_SNAKE_CASE__ : str = roberta.model.classification_heads["mnli"].dense.weight SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"].dense.bias SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head SCREAMING_SNAKE_CASE__ : Tuple = roberta.model.encoder.lm_head.dense.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.dense.bias SCREAMING_SNAKE_CASE__ : List[str] = roberta.model.encoder.lm_head.layer_norm.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta.model.encoder.lm_head.layer_norm.bias SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.encoder.lm_head.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. SCREAMING_SNAKE_CASE__ : torch.Tensor = roberta.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) # batch of size 1 SCREAMING_SNAKE_CASE__ : int = model(SCREAMING_SNAKE_CASE__ )[0] if classification_head: SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"](roberta.extract_features(SCREAMING_SNAKE_CASE__ ) ) else: SCREAMING_SNAKE_CASE__ : int = roberta.model(SCREAMING_SNAKE_CASE__ )[0] print(our_output.shape , their_output.shape ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(f'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 SCREAMING_SNAKE_CASE__ : int = torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(SCREAMING_SNAKE_CASE__ ).mkdir(parents=SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_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.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) _lowerCamelCase : Any = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
663
1
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = IFPipeline UpperCAmelCase_ = TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"} UpperCAmelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCAmelCase_ = PipelineTesterMixin.required_optional_params - {"latents"} def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" return self._get_dummy_components() def A_ ( self : Optional[Any], _UpperCAmelCase : List[str], _UpperCAmelCase : List[Any]=0 ) -> Optional[Any]: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def A_ ( self : Dict ) -> List[str]: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda", reason="float16 requires CUDA" ) def A_ ( self : str ) -> Dict: """simple docstring""" # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def A_ ( self : int ) -> Optional[Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def A_ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" self._test_save_load_local() def A_ ( self : Optional[int] ) -> Any: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2, ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available(), reason="XFormers attention is only available with CUDA and `xformers` installed", ) def A_ ( self : Tuple ) -> int: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Tuple ) -> Tuple: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : Optional[int] ) -> List[str]: """simple docstring""" # if SCREAMING_SNAKE_CASE__ : List[str] = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Optional[Any] = IFSuperResolutionPipeline.from_pretrained( "DeepFloyd/IF-II-L-v1.0", variant="fp16", torch_dtype=torch.floataa, text_encoder=_UpperCAmelCase, tokenizer=_UpperCAmelCase ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("cuda" ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = pipe_a.encode_prompt("anime turtle", device="cuda" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Dict = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img SCREAMING_SNAKE_CASE__ : Any = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE__ : int = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting SCREAMING_SNAKE_CASE__ : Optional[int] = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE__ : Optional[Any] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : str, _UpperCAmelCase : Optional[int] ) -> Union[str, Any]: """simple docstring""" # pipeline 1 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Dict = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = pipe_a( prompt_embeds=_UpperCAmelCase, negative_prompt_embeds=_UpperCAmelCase, num_inference_steps=2, generator=_UpperCAmelCase, output_type="np", ) SCREAMING_SNAKE_CASE__ : int = output.images[0] assert image.shape == (6_4, 6_4, 3) SCREAMING_SNAKE_CASE__ : Dict = torch.cuda.max_memory_allocated() assert mem_bytes < 1_3 * 1_0**9 SCREAMING_SNAKE_CASE__ : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy" ) assert_mean_pixel_difference(_UpperCAmelCase, _UpperCAmelCase ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Any = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(0 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe_a( prompt_embeds=_UpperCAmelCase, negative_prompt_embeds=_UpperCAmelCase, image=_UpperCAmelCase, generator=_UpperCAmelCase, num_inference_steps=2, output_type="np", ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy" ) assert_mean_pixel_difference(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : Optional[int] ) -> Optional[int]: """simple docstring""" # pipeline 1 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(0 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe_a( prompt_embeds=_UpperCAmelCase, negative_prompt_embeds=_UpperCAmelCase, image=_UpperCAmelCase, num_inference_steps=2, generator=_UpperCAmelCase, output_type="np", ) SCREAMING_SNAKE_CASE__ : Dict = output.images[0] assert image.shape == (6_4, 6_4, 3) SCREAMING_SNAKE_CASE__ : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 SCREAMING_SNAKE_CASE__ : List[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy" ) assert_mean_pixel_difference(_UpperCAmelCase, _UpperCAmelCase ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, 3, 2_5_6, 2_5_6), rng=random.Random(0 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(0 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = pipe_a( prompt_embeds=_UpperCAmelCase, negative_prompt_embeds=_UpperCAmelCase, image=_UpperCAmelCase, original_image=_UpperCAmelCase, generator=_UpperCAmelCase, num_inference_steps=2, output_type="np", ) SCREAMING_SNAKE_CASE__ : Any = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) SCREAMING_SNAKE_CASE__ : int = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 SCREAMING_SNAKE_CASE__ : int = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy" ) assert_mean_pixel_difference(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : List[str], _UpperCAmelCase : int, _UpperCAmelCase : Any, _UpperCAmelCase : List[str], _UpperCAmelCase : List[Any] ) -> List[str]: """simple docstring""" # pipeline 1 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(0 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(1 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe_a( prompt_embeds=_UpperCAmelCase, negative_prompt_embeds=_UpperCAmelCase, image=_UpperCAmelCase, mask_image=_UpperCAmelCase, num_inference_steps=2, generator=_UpperCAmelCase, output_type="np", ) SCREAMING_SNAKE_CASE__ : List[Any] = output.images[0] assert image.shape == (6_4, 6_4, 3) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 SCREAMING_SNAKE_CASE__ : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy" ) assert_mean_pixel_difference(_UpperCAmelCase, _UpperCAmelCase ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(0 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = floats_tensor((1, 3, 2_5_6, 2_5_6), rng=random.Random(0 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = floats_tensor((1, 3, 2_5_6, 2_5_6), rng=random.Random(1 ) ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = pipe_a( prompt_embeds=_UpperCAmelCase, negative_prompt_embeds=_UpperCAmelCase, image=_UpperCAmelCase, mask_image=_UpperCAmelCase, original_image=_UpperCAmelCase, generator=_UpperCAmelCase, num_inference_steps=2, output_type="np", ) SCREAMING_SNAKE_CASE__ : Dict = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 SCREAMING_SNAKE_CASE__ : str = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy" ) assert_mean_pixel_difference(_UpperCAmelCase, _UpperCAmelCase ) def _a ( ) -> Any: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
663
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "Wav2Vec2FeatureExtractor" UpperCAmelCase_ = "AutoTokenizer" def __init__( self : Tuple, _UpperCAmelCase : Dict, _UpperCAmelCase : Tuple ) -> List[str]: """simple docstring""" super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extractor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False @classmethod def A_ ( cls : int, _UpperCAmelCase : Dict, **_UpperCAmelCase : List[Any] ) -> Optional[int]: """simple docstring""" try: return super().from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) except OSError: warnings.warn( F'''Loading a tokenizer inside {cls.__name__} from a config that does not''' " include a `tokenizer_class` attribute is deprecated and will be " "removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`" " attribute to either your `config.json` or `tokenizer_config.json` " "file to suppress this warning: ", _UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaFeatureExtractor.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = WavaVecaCTCTokenizer.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) return cls(feature_extractor=_UpperCAmelCase, tokenizer=_UpperCAmelCase ) def __call__( self : Optional[Any], *_UpperCAmelCase : int, **_UpperCAmelCase : str ) -> Optional[Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) if "raw_speech" in kwargs: warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead." ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("raw_speech" ) else: SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop("audio", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("sampling_rate", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : Tuple = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if audio is not None: SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor(_UpperCAmelCase, *_UpperCAmelCase, sampling_rate=_UpperCAmelCase, **_UpperCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE__ : List[str] = encodings["input_ids"] return inputs def A_ ( self : Optional[Any], *_UpperCAmelCase : List[str], **_UpperCAmelCase : Optional[int] ) -> Optional[int]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("input_features", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop("labels", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : Dict = args[1:] if input_features is not None: SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor.pad(_UpperCAmelCase, *_UpperCAmelCase, **_UpperCAmelCase ) if labels is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.pad(_UpperCAmelCase, **_UpperCAmelCase ) if labels is None: return input_features elif input_features is None: return labels else: SCREAMING_SNAKE_CASE__ : List[str] = labels["input_ids"] return input_features def A_ ( self : Union[str, Any], *_UpperCAmelCase : str, **_UpperCAmelCase : Any ) -> Optional[int]: """simple docstring""" return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Optional[int], *_UpperCAmelCase : Tuple, **_UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) @contextmanager def A_ ( self : Optional[int] ) -> Any: """simple docstring""" warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your audio inputs, or in a separate call." ) SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : int = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extractor SCREAMING_SNAKE_CASE__ : Optional[Any] = False
663
1
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def _a ( ) -> Any: '''simple docstring''' import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join SCREAMING_SNAKE_CASE__ : Optional[int] = "__test_patch_submodule_mock__" with patch_submodule(_test_patching , "os.path.join" , SCREAMING_SNAKE_CASE__ ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def _a ( ) -> Any: '''simple docstring''' assert _test_patching.open is open SCREAMING_SNAKE_CASE__ : List[str] = "__test_patch_submodule_builtin_mock__" # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , "open" , SCREAMING_SNAKE_CASE__ ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def _a ( ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = "__test_patch_submodule_missing_mock__" with patch_submodule(_test_patching , "pandas.read_csv" , SCREAMING_SNAKE_CASE__ ): pass def _a ( ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = "__test_patch_submodule_missing_builtin_mock__" # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , "len" , SCREAMING_SNAKE_CASE__ ) is None with patch_submodule(_test_patching , "len" , SCREAMING_SNAKE_CASE__ ): assert _test_patching.len is mock assert _test_patching.len is len def _a ( ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = "__test_patch_submodule_start_and_stop_mock__" SCREAMING_SNAKE_CASE__ : str = patch_submodule(_test_patching , "open" , SCREAMING_SNAKE_CASE__ ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def _a ( ) -> Union[str, Any]: '''simple docstring''' from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join SCREAMING_SNAKE_CASE__ : Optional[int] = "__test_patch_submodule_successive_join__" SCREAMING_SNAKE_CASE__ : Any = "__test_patch_submodule_successive_dirname__" SCREAMING_SNAKE_CASE__ : Any = "__test_patch_submodule_successive_rename__" assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , "os.path.join" , SCREAMING_SNAKE_CASE__ ): with patch_submodule(_test_patching , "os.rename" , SCREAMING_SNAKE_CASE__ ): with patch_submodule(_test_patching , "os.path.dirname" , SCREAMING_SNAKE_CASE__ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , "os.rename" , SCREAMING_SNAKE_CASE__ ): with patch_submodule(_test_patching , "os.path.join" , SCREAMING_SNAKE_CASE__ ): with patch_submodule(_test_patching , "os.path.dirname" , SCREAMING_SNAKE_CASE__ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def _a ( ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = "__test_patch_submodule_doesnt_exist_mock__" with patch_submodule(_test_patching , "__module_that_doesn_exist__.__attribute_that_doesn_exist__" , SCREAMING_SNAKE_CASE__ ): pass with patch_submodule(_test_patching , "os.__attribute_that_doesn_exist__" , SCREAMING_SNAKE_CASE__ ): pass
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Tuple = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowerCamelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
663
1
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": _lowerCamelCase : Dict = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '''--original_config_file''', default=None, type=str, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--scheduler_type''', default='''pndm''', type=str, help='''Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']''', ) parser.add_argument( '''--pipeline_type''', default=None, type=str, help=( '''The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'''' '''. If `None` pipeline will be automatically inferred.''' ), ) parser.add_argument( '''--image_size''', default=None, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--prediction_type''', default=None, type=str, help=( '''The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable''' ''' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') parser.add_argument( '''--stable_unclip''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.''', ) parser.add_argument( '''--stable_unclip_prior''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.''', ) parser.add_argument( '''--clip_stats_path''', type=str, help='''Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.''', required=False, ) parser.add_argument( '''--controlnet''', action='''store_true''', default=None, help='''Set flag if this is a controlnet checkpoint.''' ) parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''') parser.add_argument( '''--vae_path''', type=str, default=None, required=False, help='''Set to a path, hub id to an already converted vae to not convert it again.''', ) _lowerCamelCase : List[str] = parser.parse_args() _lowerCamelCase : str = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
663
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = '''▁''' _lowerCamelCase : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''monolingual_vocab_file''': '''dict.txt'''} _lowerCamelCase : Dict = { '''vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model''', }, '''monolingual_vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt''', }, } _lowerCamelCase : Optional[Any] = {'''vinai/bartpho-syllable''': 1_0_2_4} class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = ["input_ids", "attention_mask"] def __init__( self : int, _UpperCAmelCase : Dict, _UpperCAmelCase : Tuple, _UpperCAmelCase : Any="<s>", _UpperCAmelCase : List[str]="</s>", _UpperCAmelCase : List[str]="</s>", _UpperCAmelCase : List[Any]="<s>", _UpperCAmelCase : Dict="<unk>", _UpperCAmelCase : Tuple="<pad>", _UpperCAmelCase : int="<mask>", _UpperCAmelCase : Optional[Dict[str, Any]] = None, **_UpperCAmelCase : Any, ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Any = AddedToken(_UpperCAmelCase, lstrip=_UpperCAmelCase, rstrip=_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ) else mask_token SCREAMING_SNAKE_CASE__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCAmelCase, eos_token=_UpperCAmelCase, unk_token=_UpperCAmelCase, sep_token=_UpperCAmelCase, cls_token=_UpperCAmelCase, pad_token=_UpperCAmelCase, mask_token=_UpperCAmelCase, sp_model_kwargs=self.sp_model_kwargs, **_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_file SCREAMING_SNAKE_CASE__ : Optional[int] = monolingual_vocab_file SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_UpperCAmelCase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_UpperCAmelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : Dict = cnt cnt += 1 with open(_UpperCAmelCase, "r", encoding="utf-8" ) as f: for line in f.readlines(): SCREAMING_SNAKE_CASE__ : int = line.strip().split()[0] SCREAMING_SNAKE_CASE__ : Tuple = len(self.fairseq_tokens_to_ids ) if str(_UpperCAmelCase ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : List[Any] = len(self.fairseq_tokens_to_ids ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : int = self.sp_model.serialized_model_proto() return state def __setstate__( self : int, _UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = d # for backward compatibility if not hasattr(self, "sp_model_kwargs" ): SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def A_ ( self : Optional[int], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Any = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : List[str], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None, _UpperCAmelCase : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase, token_ids_a=_UpperCAmelCase, already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1, 1] + ([0] * len(_UpperCAmelCase )) + [1] def A_ ( self : Optional[int], _UpperCAmelCase : List[int], _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A_ ( self : Any ) -> List[str]: """simple docstring""" return len(self.fairseq_ids_to_tokens ) def A_ ( self : Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = {self.convert_ids_to_tokens(_UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : Tuple, _UpperCAmelCase : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_UpperCAmelCase, out_type=_UpperCAmelCase ) def A_ ( self : List[str], _UpperCAmelCase : Union[str, Any] ) -> Tuple: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def A_ ( self : List[str], _UpperCAmelCase : str ) -> str: """simple docstring""" return self.fairseq_ids_to_tokens[index] def A_ ( self : Optional[Any], _UpperCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "".join(_UpperCAmelCase ).replace(_UpperCAmelCase, " " ).strip() return out_string def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_UpperCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join( _UpperCAmelCase, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["monolingual_vocab_file"], ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, _UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCAmelCase, "wb" ) as fi: SCREAMING_SNAKE_CASE__ : int = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _UpperCAmelCase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file, _UpperCAmelCase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_UpperCAmelCase, "w", encoding="utf-8" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F'''{str(_UpperCAmelCase )} \n''' ) return out_vocab_file, out_monolingual_vocab_file
663
1
from __future__ import annotations from random import random class lowerCamelCase : """simple docstring""" def __init__( self : List[Any], _UpperCAmelCase : int | None = None ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = value SCREAMING_SNAKE_CASE__ : List[Any] = random() SCREAMING_SNAKE_CASE__ : Node | None = None SCREAMING_SNAKE_CASE__ : Node | None = None def __repr__( self : Optional[Any] ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return F'''\'{self.value}: {self.prior:.5}\'''' else: return pformat( {F'''{self.value}: {self.prior:.5}''': (self.left, self.right)}, indent=1 ) def __str__( self : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = str(self.value ) + " " SCREAMING_SNAKE_CASE__ : Any = str(self.left or "" ) SCREAMING_SNAKE_CASE__ : Optional[int] = str(self.right or "" ) return value + left + right def _a ( SCREAMING_SNAKE_CASE__ : Node | None , SCREAMING_SNAKE_CASE__ : int ) -> tuple[Node | None, Node | None]: '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = split(root.left , SCREAMING_SNAKE_CASE__ ) return left, root else: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = split(root.right , SCREAMING_SNAKE_CASE__ ) return root, right def _a ( SCREAMING_SNAKE_CASE__ : Node | None , SCREAMING_SNAKE_CASE__ : Node | None ) -> Node | None: '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: SCREAMING_SNAKE_CASE__ : Any = merge(left.right , SCREAMING_SNAKE_CASE__ ) return left else: SCREAMING_SNAKE_CASE__ : List[str] = merge(SCREAMING_SNAKE_CASE__ , right.left ) return right def _a ( SCREAMING_SNAKE_CASE__ : Node | None , SCREAMING_SNAKE_CASE__ : int ) -> Node | None: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Node(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return merge(merge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : Node | None , SCREAMING_SNAKE_CASE__ : int ) -> Node | None: '''simple docstring''' SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[int] = split(SCREAMING_SNAKE_CASE__ , value - 1 ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return merge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : Node | None ) -> None: '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end="," ) inorder(root.right ) def _a ( SCREAMING_SNAKE_CASE__ : Node | None , SCREAMING_SNAKE_CASE__ : str ) -> Node | None: '''simple docstring''' for arg in args.split(): if arg[0] == "+": SCREAMING_SNAKE_CASE__ : Any = insert(SCREAMING_SNAKE_CASE__ , int(arg[1:] ) ) elif arg[0] == "-": SCREAMING_SNAKE_CASE__ : Dict = erase(SCREAMING_SNAKE_CASE__ , int(arg[1:] ) ) else: print("Unknown command" ) return root def _a ( ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = None print( "enter numbers to create a tree, + value to add value into treap, " "- value to erase all nodes with value. 'q' to quit. " ) SCREAMING_SNAKE_CASE__ : List[Any] = input() while args != "q": SCREAMING_SNAKE_CASE__ : List[Any] = interact_treap(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = input() print("good by!" ) if __name__ == "__main__": import doctest doctest.testmod() main()
663
from random import shuffle import tensorflow as tf from numpy import array def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = int(SCREAMING_SNAKE_CASE__ ) assert noofclusters < len(SCREAMING_SNAKE_CASE__ ) # Find out the dimensionality SCREAMING_SNAKE_CASE__ : List[Any] = len(vectors[0] ) # Will help select random centroids from among the available vectors SCREAMING_SNAKE_CASE__ : List[Any] = list(range(len(SCREAMING_SNAKE_CASE__ ) ) ) shuffle(SCREAMING_SNAKE_CASE__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. SCREAMING_SNAKE_CASE__ : Tuple = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION SCREAMING_SNAKE_CASE__ : List[Any] = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points SCREAMING_SNAKE_CASE__ : Any = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(SCREAMING_SNAKE_CASE__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("float64" , [dim] ) SCREAMING_SNAKE_CASE__ : Dict = [] for centroid in centroids: cent_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) SCREAMING_SNAKE_CASE__ : Tuple = [tf.Variable(0 ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value SCREAMING_SNAKE_CASE__ : Tuple = tf.placeholder("int32" ) SCREAMING_SNAKE_CASE__ : Tuple = [] for assignment in assignments: cluster_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input SCREAMING_SNAKE_CASE__ : int = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors SCREAMING_SNAKE_CASE__ : str = tf.reduce_mean(SCREAMING_SNAKE_CASE__ , 0 ) ##Node for computing Euclidean distances # Placeholders for input SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.placeholder("float" , [dim] ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("float" , [dim] ) SCREAMING_SNAKE_CASE__ : Dict = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.placeholder("float" , [noofclusters] ) SCREAMING_SNAKE_CASE__ : Tuple = tf.argmin(SCREAMING_SNAKE_CASE__ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. SCREAMING_SNAKE_CASE__ : Tuple = tf.initialize_all_variables() # Initialize all variables sess.run(SCREAMING_SNAKE_CASE__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. SCREAMING_SNAKE_CASE__ : Tuple = 1_00 for _ in range(SCREAMING_SNAKE_CASE__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(SCREAMING_SNAKE_CASE__ ) ): SCREAMING_SNAKE_CASE__ : Any = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. SCREAMING_SNAKE_CASE__ : Tuple = [ sess.run(SCREAMING_SNAKE_CASE__ , feed_dict={va: vect, va: sess.run(SCREAMING_SNAKE_CASE__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input SCREAMING_SNAKE_CASE__ : Any = sess.run( SCREAMING_SNAKE_CASE__ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(SCREAMING_SNAKE_CASE__ ): # Collect all the vectors assigned to this cluster SCREAMING_SNAKE_CASE__ : Dict = [ vectors[i] for i in range(len(SCREAMING_SNAKE_CASE__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location SCREAMING_SNAKE_CASE__ : str = sess.run( SCREAMING_SNAKE_CASE__ , feed_dict={mean_input: array(SCREAMING_SNAKE_CASE__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments SCREAMING_SNAKE_CASE__ : int = sess.run(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = sess.run(SCREAMING_SNAKE_CASE__ ) return centroids, assignments
663
1
import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = MobileBertConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = MobileBertForPreTraining(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint SCREAMING_SNAKE_CASE__ : Tuple = load_tf_weights_in_mobilebert(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _lowerCamelCase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--mobilebert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained MobileBERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase : int = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
663
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) _lowerCamelCase : List[str] = None _lowerCamelCase : Union[str, Any] = { '''7B''': 1_1_0_0_8, '''13B''': 1_3_8_2_4, '''30B''': 1_7_9_2_0, '''65B''': 2_2_0_1_6, '''70B''': 2_8_6_7_2, } _lowerCamelCase : Optional[Any] = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : str=2_56 ) -> int: '''simple docstring''' return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def _a ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ , "r" ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str=True ) -> int: '''simple docstring''' os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , "tmp" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = read_json(os.path.join(SCREAMING_SNAKE_CASE__ , "params.json" ) ) SCREAMING_SNAKE_CASE__ : int = NUM_SHARDS[model_size] SCREAMING_SNAKE_CASE__ : Union[str, Any] = params["n_layers"] SCREAMING_SNAKE_CASE__ : List[str] = params["n_heads"] SCREAMING_SNAKE_CASE__ : Optional[Any] = n_heads // num_shards SCREAMING_SNAKE_CASE__ : str = params["dim"] SCREAMING_SNAKE_CASE__ : List[str] = dim // n_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_0_0_0_0.0 SCREAMING_SNAKE_CASE__ : Tuple = 1.0 / (base ** (torch.arange(0 , SCREAMING_SNAKE_CASE__ , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: SCREAMING_SNAKE_CASE__ : int = params["n_kv_heads"] # for GQA / MQA SCREAMING_SNAKE_CASE__ : Optional[int] = n_heads_per_shard // num_key_value_heads SCREAMING_SNAKE_CASE__ : int = dim // num_key_value_heads else: # compatibility with other checkpoints SCREAMING_SNAKE_CASE__ : Dict = n_heads SCREAMING_SNAKE_CASE__ : str = n_heads_per_shard SCREAMING_SNAKE_CASE__ : Dict = dim # permute for sliced rotary def permute(SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=n_heads , SCREAMING_SNAKE_CASE__ : List[str]=dim , SCREAMING_SNAKE_CASE__ : Dict=dim ): return w.view(SCREAMING_SNAKE_CASE__ , dima // n_heads // 2 , 2 , SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'''Fetching all parameters from the checkpoint at {input_base_path}.''' ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) SCREAMING_SNAKE_CASE__ : Dict = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , "consolidated.00.pth" ) , map_location="cpu" ) else: # Sharded SCREAMING_SNAKE_CASE__ : List[Any] = [ torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , f'''consolidated.{i:02d}.pth''' ) , map_location="cpu" ) for i in range(SCREAMING_SNAKE_CASE__ ) ] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : List[str] = {"weight_map": {}} for layer_i in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded SCREAMING_SNAKE_CASE__ : List[Any] = { f'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wq.weight'''] ), f'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wk.weight'''] ), f'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[f'''layers.{layer_i}.attention.wv.weight'''], f'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[f'''layers.{layer_i}.attention.wo.weight'''], f'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w1.weight'''], f'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w2.weight'''], f'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w3.weight'''], f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[f'''layers.{layer_i}.attention_norm.weight'''], f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[f'''layers.{layer_i}.ffn_norm.weight'''], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. SCREAMING_SNAKE_CASE__ : Any = { f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.attention_norm.weight''' ].clone(), f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.ffn_norm.weight''' ].clone(), } SCREAMING_SNAKE_CASE__ : int = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wq.weight'''].view(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : Tuple = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wk.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wv.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = torch.cat( [loaded[i][f'''layers.{layer_i}.attention.wo.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : int = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) SCREAMING_SNAKE_CASE__ : List[str] = inv_freq for k, v in state_dict.items(): SCREAMING_SNAKE_CASE__ : str = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded SCREAMING_SNAKE_CASE__ : List[str] = { "model.embed_tokens.weight": loaded["tok_embeddings.weight"], "model.norm.weight": loaded["norm.weight"], "lm_head.weight": loaded["output.weight"], } else: SCREAMING_SNAKE_CASE__ : Optional[Any] = { "model.norm.weight": loaded[0]["norm.weight"], "model.embed_tokens.weight": torch.cat( [loaded[i]["tok_embeddings.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ), "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ), } for k, v in state_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[int] = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Write configs SCREAMING_SNAKE_CASE__ : Optional[Any] = {"total_size": param_count * 2} write_json(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , "pytorch_model.bin.index.json" ) ) SCREAMING_SNAKE_CASE__ : List[str] = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1 SCREAMING_SNAKE_CASE__ : Dict = params["multiple_of"] if "multiple_of" in params else 2_56 SCREAMING_SNAKE_CASE__ : Dict = LlamaConfig( hidden_size=SCREAMING_SNAKE_CASE__ , intermediate_size=compute_intermediate_size(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , num_attention_heads=params["n_heads"] , num_hidden_layers=params["n_layers"] , rms_norm_eps=params["norm_eps"] , num_key_value_heads=SCREAMING_SNAKE_CASE__ , ) config.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("Loading the checkpoint in a Llama model." ) SCREAMING_SNAKE_CASE__ : int = LlamaForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa , low_cpu_mem_usage=SCREAMING_SNAKE_CASE__ ) # Avoid saving this as part of the config. del model.config._name_or_path print("Saving in the Transformers format." ) model.save_pretrained(SCREAMING_SNAKE_CASE__ , safe_serialization=SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(f'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer_class(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) def _a ( ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() parser.add_argument( "--input_dir" , help="Location of LLaMA weights, which contains tokenizer.model and model folders" , ) parser.add_argument( "--model_size" , choices=["7B", "7Bf", "13B", "13Bf", "30B", "65B", "70B", "70Bf", "tokenizer_only"] , ) parser.add_argument( "--output_dir" , help="Location to write HF model and tokenizer" , ) parser.add_argument("--safe_serialization" , type=SCREAMING_SNAKE_CASE__ , help="Whether or not to save using `safetensors`." ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(args.input_dir , "tokenizer.model" ) write_tokenizer(args.output_dir , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
663
1
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : Union[str, Any] = get_tests_dir('''fixtures/spiece.model''') @require_sentencepiece @require_tokenizers class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = DebertaVaTokenizer UpperCAmelCase_ = DebertaVaTokenizerFast UpperCAmelCase_ = True UpperCAmelCase_ = True def A_ ( self : str ) -> Tuple: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Any = DebertaVaTokenizer(_UpperCAmelCase, unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def A_ ( self : str, _UpperCAmelCase : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = "this is a test" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "this is a test" return input_text, output_text def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = "<pad>" SCREAMING_SNAKE_CASE__ : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ), _UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], "<pad>" ) self.assertEqual(vocab_keys[1], "<unk>" ) self.assertEqual(vocab_keys[-1], "[PAD]" ) self.assertEqual(len(_UpperCAmelCase ), 3_0_0_0_1 ) def A_ ( self : Optional[int] ) -> Dict: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size, 3_0_0_0_0 ) def A_ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = " \tHeLLo!how \n Are yoU? " SCREAMING_SNAKE_CASE__ : Tuple = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on SCREAMING_SNAKE_CASE__ : int = DebertaVaTokenizer(_UpperCAmelCase, do_lower_case=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = DebertaVaTokenizerFast(_UpperCAmelCase, do_lower_case=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def A_ ( self : int ) -> str: """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def A_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" pass def A_ ( self : str ) -> Tuple: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : str = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE__ : Any = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on SCREAMING_SNAKE_CASE__ : Any = DebertaVaTokenizer(_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = DebertaVaTokenizerFast(_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : int ) -> Tuple: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : str = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE__ : Dict = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on SCREAMING_SNAKE_CASE__ : Any = DebertaVaTokenizer(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.convert_ids_to_tokens(tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = DebertaVaTokenizerFast(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Any = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE__ : List[Any] = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on SCREAMING_SNAKE_CASE__ : Optional[int] = DebertaVaTokenizer(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = DebertaVaTokenizerFast(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Any ) -> Optional[int]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Any = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE__ : int = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on SCREAMING_SNAKE_CASE__ : Tuple = DebertaVaTokenizer(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.convert_ids_to_tokens(tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = DebertaVaTokenizerFast(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Dict ) -> int: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : str = " \tHeLLo!how \n Are yoU? " SCREAMING_SNAKE_CASE__ : Optional[Any] = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on SCREAMING_SNAKE_CASE__ : Any = DebertaVaTokenizer(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DebertaVaTokenizerFast(_UpperCAmelCase, do_lower_case=_UpperCAmelCase, split_by_punct=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : int = tokenizer.encode(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = "This is a test" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] SCREAMING_SNAKE_CASE__ : Dict = ["▁", "T", "his", "▁is", "▁a", "▁test"] SCREAMING_SNAKE_CASE__ : str = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] SCREAMING_SNAKE_CASE__ : List[Any] = DebertaVaTokenizer(_UpperCAmelCase, keep_accents=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = DebertaVaTokenizerFast(_UpperCAmelCase, keep_accents=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = rust_tokenizer.convert_ids_to_tokens(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # fmt: off SCREAMING_SNAKE_CASE__ : Any = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE__ : Any = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] SCREAMING_SNAKE_CASE__ : Dict = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] SCREAMING_SNAKE_CASE__ : List[str] = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.convert_ids_to_tokens(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.convert_ids_to_tokens(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DebertaVaTokenizer(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode("sequence builders" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode("multi-sequence build" ) SCREAMING_SNAKE_CASE__ : str = tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase, _UpperCAmelCase ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id], _UpperCAmelCase ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id], _UpperCAmelCase, ) @slow def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase, model_name="microsoft/deberta-v2-xlarge", revision="ad6e42c1532ddf3a15c39246b63f5559d558b670", )
663
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = GPTaTokenizer UpperCAmelCase_ = GPTaTokenizerFast UpperCAmelCase_ = True UpperCAmelCase_ = {"add_prefix_space": True} UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : Any = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] SCREAMING_SNAKE_CASE__ : int = dict(zip(_UpperCAmelCase, range(len(_UpperCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE__ : str = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] SCREAMING_SNAKE_CASE__ : Any = {"unk_token": "<unk>"} SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file, "w", encoding="utf-8" ) as fp: fp.write(json.dumps(_UpperCAmelCase ) + "\n" ) with open(self.merges_file, "w", encoding="utf-8" ) as fp: fp.write("\n".join(_UpperCAmelCase ) ) def A_ ( self : Tuple, **_UpperCAmelCase : str ) -> str: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : int, **_UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname, **_UpperCAmelCase ) def A_ ( self : Tuple, _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = "lower newer" SCREAMING_SNAKE_CASE__ : List[Any] = "lower newer" return input_text, output_text def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Tuple = "lower newer" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] SCREAMING_SNAKE_CASE__ : Dict = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Dict = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Dict ) -> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = "lower newer" # Testing tokenization SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE__ : Tuple = self.get_rust_tokenizer(add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(_UpperCAmelCase, add_prefix_space=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) # Testing the unknown token SCREAMING_SNAKE_CASE__ : Dict = tokens + [rust_tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : str = [1_4, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) def A_ ( self : Tuple, *_UpperCAmelCase : List[Any], **_UpperCAmelCase : Union[str, Any] ) -> Optional[int]: """simple docstring""" # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def A_ ( self : Optional[Any], _UpperCAmelCase : int=1_5 ) -> List[str]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Any = self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase, **_UpperCAmelCase ) # Simple input SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : List[str] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Any = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : List[Any] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Simple input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises(_UpperCAmelCase, tokenizer_r.encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length" ) # Pair input self.assertRaises( _UpperCAmelCase, tokenizer_r.batch_encode_plus, _UpperCAmelCase, max_length=_UpperCAmelCase, padding="max_length", ) def A_ ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = GPTaTokenizer.from_pretrained(self.tmpdirname, pad_token="<pad>" ) # Simple input SCREAMING_SNAKE_CASE__ : Union[str, Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Dict = ["This is a simple input looooooooong", "This is a simple input"] SCREAMING_SNAKE_CASE__ : List[str] = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : int = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding="max_length", max_length=3_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(*_UpperCAmelCase, padding="max_length", max_length=6_0, return_tensors="np" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_UpperCAmelCase, padding=_UpperCAmelCase, truncate=_UpperCAmelCase, return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1], 3_0 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1], 3_3 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1], 6_0 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1], 5_2 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "$$$" SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizer.from_pretrained(self.tmpdirname, bos_token=_UpperCAmelCase, add_bos_token=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(_UpperCAmelCase ) self.assertEqual(out_s.input_ids[0], _UpperCAmelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.decode(out_s.input_ids ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], _UpperCAmelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def A_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" pass def A_ ( self : Dict ) -> str: """simple docstring""" # TODO: change to self.get_tokenizers() when the fast version is implemented SCREAMING_SNAKE_CASE__ : Any = [self.get_tokenizer(do_lower_case=_UpperCAmelCase, add_bos_token=_UpperCAmelCase )] for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ : List[Any] = "Encode this." SCREAMING_SNAKE_CASE__ : Optional[Any] = "This one too please." SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) encoded_sequence += tokenizer.encode(_UpperCAmelCase, add_special_tokens=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode_plus( _UpperCAmelCase, _UpperCAmelCase, add_special_tokens=_UpperCAmelCase, return_special_tokens_mask=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Any = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(_UpperCAmelCase ), len(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(_UpperCAmelCase ) ] SCREAMING_SNAKE_CASE__ : List[Any] = [x for x in filtered_sequence if x is not None] self.assertEqual(_UpperCAmelCase, _UpperCAmelCase ) @require_tokenizers class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : Optional[Any] ) -> int: """simple docstring""" # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("test_opt" ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("./test_opt" ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m", use_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = "A photo of a cat" SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode( _UpperCAmelCase, ) # Same as above self.assertEqual(_UpperCAmelCase, [2, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) @unittest.skip("This test is failing because of a bug in the fast tokenizer" ) def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = "bos" SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.get_vocab()["bos"] SCREAMING_SNAKE_CASE__ : Tuple = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode( _UpperCAmelCase, ) # We changed the bos token self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] ) tokenizer.save_pretrained("./tok" ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained("./tok" ) self.assertTrue(tokenizer.is_fast ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _UpperCAmelCase, ) self.assertEqual(_UpperCAmelCase, [3_1_9_5_7, 2_5_0, 1_3_4_5, 9, 1_0, 4_7_5_8] )
663
1
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" @require_torch def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = pipeline( task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused" ) SCREAMING_SNAKE_CASE__ : int = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : int = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> Dict: """simple docstring""" pass @slow @require_torch def A_ ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pipeline( task="zero-shot-audio-classification", model="laion/clap-htsat-unfused", ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ : List[str] = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Optional[Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier( [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5 ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> List[str]: """simple docstring""" pass
663
from functools import lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> set: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(SCREAMING_SNAKE_CASE__ ) if n > 1: factors.add(SCREAMING_SNAKE_CASE__ ) return factors @lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' return len(unique_prime_factors(SCREAMING_SNAKE_CASE__ ) ) def _a ( SCREAMING_SNAKE_CASE__ : list ) -> bool: '''simple docstring''' return len(set(SCREAMING_SNAKE_CASE__ ) ) in (0, 1) def _a ( SCREAMING_SNAKE_CASE__ : int ) -> list: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 2 while True: # Increment each value of a generated range SCREAMING_SNAKE_CASE__ : List[str] = [base + i for i in range(SCREAMING_SNAKE_CASE__ )] # Run elements through out unique_prime_factors function # Append our target number to the end. SCREAMING_SNAKE_CASE__ : Tuple = [upf_len(SCREAMING_SNAKE_CASE__ ) for x in group] checker.append(SCREAMING_SNAKE_CASE__ ) # If all numbers in the list are equal, return the group variable. if equality(SCREAMING_SNAKE_CASE__ ): return group # Increment our base variable by 1 base += 1 def _a ( SCREAMING_SNAKE_CASE__ : int = 4 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = run(SCREAMING_SNAKE_CASE__ ) return results[0] if len(SCREAMING_SNAKE_CASE__ ) else None if __name__ == "__main__": print(solution())
663
1
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 _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): return image elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ : Dict = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ : List[str] = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 ) SCREAMING_SNAKE_CASE__ : List[str] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ : Optional[Any] = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ : str = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) return image def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any=0.9_9_9_5 ) -> Dict: '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Any = va.device SCREAMING_SNAKE_CASE__ : Any = va.cpu().numpy() SCREAMING_SNAKE_CASE__ : Union[str, Any] = va.cpu().numpy() SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) ) if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD: SCREAMING_SNAKE_CASE__ : List[str] = (1 - t) * va + t * va else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = np.sin(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = theta_a * t SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.sin(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.sin(theta_a - theta_t ) / sin_theta_a SCREAMING_SNAKE_CASE__ : Tuple = sin_theta_t / sin_theta_a SCREAMING_SNAKE_CASE__ : int = sa * va + sa * va if inputs_are_torch: SCREAMING_SNAKE_CASE__ : Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) return va def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) SCREAMING_SNAKE_CASE__ : Tuple = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def _a ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: '''simple docstring''' for param in model.parameters(): SCREAMING_SNAKE_CASE__ : str = value class lowerCamelCase (__lowerCamelCase ): """simple docstring""" def __init__( self : List[str], _UpperCAmelCase : AutoencoderKL, _UpperCAmelCase : CLIPTextModel, _UpperCAmelCase : CLIPModel, _UpperCAmelCase : CLIPTokenizer, _UpperCAmelCase : UNetaDConditionModel, _UpperCAmelCase : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler], _UpperCAmelCase : CLIPFeatureExtractor, _UpperCAmelCase : Optional[int]=None, _UpperCAmelCase : int=None, _UpperCAmelCase : Any=None, ) -> Dict: """simple docstring""" super().__init__() self.register_modules( vae=_UpperCAmelCase, text_encoder=_UpperCAmelCase, clip_model=_UpperCAmelCase, tokenizer=_UpperCAmelCase, unet=_UpperCAmelCase, scheduler=_UpperCAmelCase, feature_extractor=_UpperCAmelCase, coca_model=_UpperCAmelCase, coca_tokenizer=_UpperCAmelCase, coca_transform=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : str = ( feature_extractor.size if isinstance(feature_extractor.size, _UpperCAmelCase ) else feature_extractor.size["shortest_edge"] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std ) set_requires_grad(self.text_encoder, _UpperCAmelCase ) set_requires_grad(self.clip_model, _UpperCAmelCase ) def A_ ( self : int, _UpperCAmelCase : Optional[Union[str, int]] = "auto" ) -> Dict: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE__ : List[Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" self.enable_attention_slicing(_UpperCAmelCase ) def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" set_requires_grad(self.vae, _UpperCAmelCase ) def A_ ( self : int ) -> Optional[int]: """simple docstring""" set_requires_grad(self.vae, _UpperCAmelCase ) def A_ ( self : Dict ) -> int: """simple docstring""" set_requires_grad(self.unet, _UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" set_requires_grad(self.unet, _UpperCAmelCase ) def A_ ( self : List[str], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int, _UpperCAmelCase : List[Any] ) -> Optional[Any]: """simple docstring""" # get the original timestep using init_timestep SCREAMING_SNAKE_CASE__ : Optional[int] = min(int(num_inference_steps * strength ), _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = max(num_inference_steps - init_timestep, 0 ) SCREAMING_SNAKE_CASE__ : Dict = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def A_ ( self : Tuple, _UpperCAmelCase : Any, _UpperCAmelCase : Tuple, _UpperCAmelCase : Dict, _UpperCAmelCase : Any, _UpperCAmelCase : Tuple, _UpperCAmelCase : str=None ) -> List[str]: """simple docstring""" if not isinstance(_UpperCAmelCase, torch.Tensor ): raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(_UpperCAmelCase )}''' ) SCREAMING_SNAKE_CASE__ : Tuple = image.to(device=_UpperCAmelCase, dtype=_UpperCAmelCase ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_UpperCAmelCase ) ] SCREAMING_SNAKE_CASE__ : str = torch.cat(_UpperCAmelCase, dim=0 ) else: SCREAMING_SNAKE_CASE__ : List[Any] = self.vae.encode(_UpperCAmelCase ).latent_dist.sample(_UpperCAmelCase ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0.18215 * init_latents SCREAMING_SNAKE_CASE__ : Union[str, Any] = init_latents.repeat_interleave(_UpperCAmelCase, dim=0 ) SCREAMING_SNAKE_CASE__ : Dict = randn_tensor(init_latents.shape, generator=_UpperCAmelCase, device=_UpperCAmelCase, dtype=_UpperCAmelCase ) # get latents SCREAMING_SNAKE_CASE__ : str = self.scheduler.add_noise(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = init_latents return latents def A_ ( self : Any, _UpperCAmelCase : Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.coca_transform(_UpperCAmelCase ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE__ : str = self.coca_model.generate(transformed_image.to(device=self.device, dtype=self.coca_model.dtype ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split("<end_of_text>" )[0].replace("<start_of_text>", "" ).rstrip(" .," ) def A_ ( self : Optional[int], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extractor.preprocess(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.from_numpy(clip_image_input["pixel_values"][0] ).unsqueeze(0 ).to(self.device ).half() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.clip_model.get_image_features(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = image_embeddings_clip.repeat_interleave(_UpperCAmelCase, dim=0 ) return image_embeddings_clip @torch.enable_grad() def A_ ( self : Optional[Any], _UpperCAmelCase : Any, _UpperCAmelCase : List[Any], _UpperCAmelCase : Dict, _UpperCAmelCase : str, _UpperCAmelCase : List[str], _UpperCAmelCase : str, _UpperCAmelCase : Optional[int], ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = latents.detach().requires_grad_() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) # predict the noise residual SCREAMING_SNAKE_CASE__ : Tuple = self.unet(_UpperCAmelCase, _UpperCAmelCase, encoder_hidden_states=_UpperCAmelCase ).sample if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : str = 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 SCREAMING_SNAKE_CASE__ : Optional[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : str = torch.sqrt(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : str = self.scheduler.sigmas[index] SCREAMING_SNAKE_CASE__ : Optional[int] = 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 SCREAMING_SNAKE_CASE__ : Tuple = 1 / 0.18215 * sample SCREAMING_SNAKE_CASE__ : List[str] = self.vae.decode(_UpperCAmelCase ).sample SCREAMING_SNAKE_CASE__ : Optional[int] = (image / 2 + 0.5).clamp(0, 1 ) SCREAMING_SNAKE_CASE__ : Dict = transforms.Resize(self.feature_extractor_size )(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = self.normalize(_UpperCAmelCase ).to(latents.dtype ) SCREAMING_SNAKE_CASE__ : List[Any] = self.clip_model.get_image_features(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = spherical_dist_loss(_UpperCAmelCase, _UpperCAmelCase ).mean() * clip_guidance_scale SCREAMING_SNAKE_CASE__ : List[Any] = -torch.autograd.grad(_UpperCAmelCase, _UpperCAmelCase )[0] if isinstance(self.scheduler, _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach() + grads * (sigma**2) SCREAMING_SNAKE_CASE__ : int = noise_pred_original else: SCREAMING_SNAKE_CASE__ : Any = noise_pred_original - torch.sqrt(_UpperCAmelCase ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Optional[Any], _UpperCAmelCase : Union[torch.FloatTensor, PIL.Image.Image], _UpperCAmelCase : Union[torch.FloatTensor, PIL.Image.Image], _UpperCAmelCase : Optional[str] = None, _UpperCAmelCase : Optional[str] = None, _UpperCAmelCase : Optional[int] = 5_1_2, _UpperCAmelCase : Optional[int] = 5_1_2, _UpperCAmelCase : float = 0.6, _UpperCAmelCase : Optional[int] = 5_0, _UpperCAmelCase : Optional[float] = 7.5, _UpperCAmelCase : Optional[int] = 1, _UpperCAmelCase : float = 0.0, _UpperCAmelCase : Optional[float] = 1_0_0, _UpperCAmelCase : Optional[torch.Generator] = None, _UpperCAmelCase : Optional[str] = "pil", _UpperCAmelCase : bool = True, _UpperCAmelCase : float = 0.8, _UpperCAmelCase : float = 0.1, _UpperCAmelCase : float = 0.1, ) -> Optional[int]: """simple docstring""" if isinstance(_UpperCAmelCase, _UpperCAmelCase ) and len(_UpperCAmelCase ) != batch_size: raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(_UpperCAmelCase )} 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(_UpperCAmelCase, torch.Generator ) and batch_size > 1: SCREAMING_SNAKE_CASE__ : Tuple = [generator] + [None] * (batch_size - 1) SCREAMING_SNAKE_CASE__ : Any = [ ("model", self.coca_model is None), ("tokenizer", self.coca_tokenizer is None), ("transform", self.coca_transform is None), ] SCREAMING_SNAKE_CASE__ : List[str] = [x[0] for x in coca_is_none if x[1]] SCREAMING_SNAKE_CASE__ : Optional[int] = ", ".join(_UpperCAmelCase ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(_UpperCAmelCase ): 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.''' ) SCREAMING_SNAKE_CASE__ : str = self.get_image_description(_UpperCAmelCase ) if style_prompt is None: if len(_UpperCAmelCase ): 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.''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_image_description(_UpperCAmelCase ) # get prompt text embeddings for content and style SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer( _UpperCAmelCase, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=_UpperCAmelCase, return_tensors="pt", ) SCREAMING_SNAKE_CASE__ : List[Any] = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer( _UpperCAmelCase, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=_UpperCAmelCase, return_tensors="pt", ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] SCREAMING_SNAKE_CASE__ : str = slerp(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # duplicate text embeddings for each generation per prompt SCREAMING_SNAKE_CASE__ : str = text_embeddings.repeat_interleave(_UpperCAmelCase, dim=0 ) # set timesteps SCREAMING_SNAKE_CASE__ : Any = "offset" in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) SCREAMING_SNAKE_CASE__ : str = {} if accepts_offset: SCREAMING_SNAKE_CASE__ : List[str] = 1 self.scheduler.set_timesteps(_UpperCAmelCase, **_UpperCAmelCase ) # 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 ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_timesteps(_UpperCAmelCase, _UpperCAmelCase, self.device ) SCREAMING_SNAKE_CASE__ : Optional[Any] = timesteps[:1].repeat(_UpperCAmelCase ) # Preprocess image SCREAMING_SNAKE_CASE__ : Union[str, Any] = preprocess(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_latents( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, text_embeddings.dtype, self.device, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = preprocess(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_latents( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, text_embeddings.dtype, self.device, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = slerp(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) if clip_guidance_scale > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_clip_image_embeddings(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_clip_image_embeddings(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = slerp( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # 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. SCREAMING_SNAKE_CASE__ : Optional[Any] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ : List[str] = content_text_input.input_ids.shape[-1] SCREAMING_SNAKE_CASE__ : str = self.tokenizer([""], padding="max_length", max_length=_UpperCAmelCase, return_tensors="pt" ) SCREAMING_SNAKE_CASE__ : Tuple = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt SCREAMING_SNAKE_CASE__ : Optional[Any] = uncond_embeddings.repeat_interleave(_UpperCAmelCase, 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 SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. SCREAMING_SNAKE_CASE__ : Dict = (batch_size, self.unet.config.in_channels, height // 8, width // 8) SCREAMING_SNAKE_CASE__ : Optional[Any] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.randn(_UpperCAmelCase, generator=_UpperCAmelCase, device="cpu", dtype=_UpperCAmelCase ).to( self.device ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.randn(_UpperCAmelCase, generator=_UpperCAmelCase, device=self.device, dtype=_UpperCAmelCase ) else: if latents.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) SCREAMING_SNAKE_CASE__ : int = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE__ : int = 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] SCREAMING_SNAKE_CASE__ : str = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {} if accepts_eta: SCREAMING_SNAKE_CASE__ : str = eta # check if the scheduler accepts generator SCREAMING_SNAKE_CASE__ : List[Any] = "generator" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: SCREAMING_SNAKE_CASE__ : Optional[Any] = generator with self.progress_bar(total=_UpperCAmelCase ): for i, t in enumerate(_UpperCAmelCase ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE__ : int = self.scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) # predict the noise residual SCREAMING_SNAKE_CASE__ : Optional[int] = self.unet(_UpperCAmelCase, _UpperCAmelCase, encoder_hidden_states=_UpperCAmelCase ).sample # perform classifier free guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ : List[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: SCREAMING_SNAKE_CASE__ : Dict = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = self.cond_fn( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : Dict = self.scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, **_UpperCAmelCase ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor SCREAMING_SNAKE_CASE__ : List[Any] = 1 / 0.18215 * latents SCREAMING_SNAKE_CASE__ : List[Any] = self.vae.decode(_UpperCAmelCase ).sample SCREAMING_SNAKE_CASE__ : Any = (image / 2 + 0.5).clamp(0, 1 ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0, 2, 3, 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : Any = self.numpy_to_pil(_UpperCAmelCase ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=_UpperCAmelCase, nsfw_content_detected=_UpperCAmelCase )
663
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" @require_torch def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = pipeline( task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused" ) SCREAMING_SNAKE_CASE__ : int = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : int = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> Dict: """simple docstring""" pass @slow @require_torch def A_ ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pipeline( task="zero-shot-audio-classification", model="laion/clap-htsat-unfused", ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ : List[str] = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Optional[Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier( [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5 ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> List[str]: """simple docstring""" pass
663
1
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 : int, _UpperCAmelCase : Any, _UpperCAmelCase : Tuple=1_3, _UpperCAmelCase : List[Any]=3_0, _UpperCAmelCase : Dict=2, _UpperCAmelCase : Optional[Any]=3, _UpperCAmelCase : Tuple=True, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Any=3_2, _UpperCAmelCase : Dict=5, _UpperCAmelCase : Union[str, Any]=4, _UpperCAmelCase : Union[str, Any]=3_7, _UpperCAmelCase : Dict="gelu", _UpperCAmelCase : Dict=0.1, _UpperCAmelCase : Tuple=0.1, _UpperCAmelCase : List[str]=1_0, _UpperCAmelCase : int=0.02, ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : int = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : Dict = use_labels SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : str = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Tuple = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str = num_patches + 1 def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = 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=_UpperCAmelCase, initializer_range=self.initializer_range, ) return config, pixel_values def A_ ( self : Union[str, Any], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = FlaxViTModel(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = model(_UpperCAmelCase ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : int = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE__ : Optional[Any] = (self.patch_size, self.patch_size) SCREAMING_SNAKE_CASE__ : Dict = (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 A_ ( self : Any, _UpperCAmelCase : Dict, _UpperCAmelCase : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = FlaxViTForImageClassification(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = model(_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE__ : Tuple = FlaxViTForImageClassification(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) ,( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def A_ ( self : List[Any] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxViTModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple = ConfigTester(self, config_class=_UpperCAmelCase, has_text_modality=_UpperCAmelCase, hidden_size=3_7 ) def A_ ( self : str ) -> str: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> List[Any]: """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: SCREAMING_SNAKE_CASE__ : Any = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Optional[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[int] = 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__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = model_class(_UpperCAmelCase ) @jax.jit def model_jitted(_UpperCAmelCase : List[Any], **_UpperCAmelCase : List[str] ): return model(pixel_values=_UpperCAmelCase, **_UpperCAmelCase ) with self.subTest("JIT Enabled" ): SCREAMING_SNAKE_CASE__ : Tuple = model_jitted(**_UpperCAmelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_jitted(**_UpperCAmelCase ).to_tuple() self.assertEqual(len(_UpperCAmelCase ), len(_UpperCAmelCase ) ) for jitted_output, output in zip(_UpperCAmelCase, _UpperCAmelCase ): self.assertEqual(jitted_output.shape, output.shape ) @slow def A_ ( self : Optional[Any] ) -> Tuple: """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__ : Any = model(np.ones((1, 3, 2_2_4, 2_2_4) ) ) self.assertIsNotNone(_UpperCAmelCase )
663
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase : List[str] = 2_0_0 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase : Any = 5_0 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase : str = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1_0_0_0)) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, float]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = len([g for position, g in enumerate(SCREAMING_SNAKE_CASE__ ) if g == main_target[position]] ) return (item, float(SCREAMING_SNAKE_CASE__ )) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> tuple[str, str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) SCREAMING_SNAKE_CASE__ : Tuple = parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE__ : str = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = list(SCREAMING_SNAKE_CASE__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE__ : Tuple = random.choice(SCREAMING_SNAKE_CASE__ ) return "".join(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : tuple[str, float] , SCREAMING_SNAKE_CASE__ : list[tuple[str, float]] , SCREAMING_SNAKE_CASE__ : list[str] , ) -> list[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE__ : List[str] = int(parent_a[1] * 1_00 ) + 1 SCREAMING_SNAKE_CASE__ : Tuple = 10 if child_n >= 10 else child_n for _ in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = population_score[random.randint(0 , SCREAMING_SNAKE_CASE__ )][0] SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = crossover(parent_a[0] , SCREAMING_SNAKE_CASE__ ) # Append new string to the population list. pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) return pop def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] , SCREAMING_SNAKE_CASE__ : bool = True ) -> tuple[int, int, str]: '''simple docstring''' if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE__ : str = f'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE__ : Optional[int] = sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE__ : Dict = f'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Generate random starting population. SCREAMING_SNAKE_CASE__ : List[Any] = [] for _ in range(SCREAMING_SNAKE_CASE__ ): population.append("".join([random.choice(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(SCREAMING_SNAKE_CASE__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE__ : int = [evaluate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE__ : List[str] = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[1] , reverse=SCREAMING_SNAKE_CASE__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f'''\nGeneration: {generation}''' f'''\nTotal Population:{total_population}''' f'''\nBest score: {population_score[0][1]}''' f'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE__ : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(SCREAMING_SNAKE_CASE__ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ (item, score / len(SCREAMING_SNAKE_CASE__ )) for item, score in population_score ] # This is selection for i in range(SCREAMING_SNAKE_CASE__ ): population.extend(select(population_score[int(SCREAMING_SNAKE_CASE__ )] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(SCREAMING_SNAKE_CASE__ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase : Dict = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) _lowerCamelCase : Tuple = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = basic(target_str, genes_list) print( f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
663
1
from functools import lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> set: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(SCREAMING_SNAKE_CASE__ ) if n > 1: factors.add(SCREAMING_SNAKE_CASE__ ) return factors @lru_cache def _a ( SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' return len(unique_prime_factors(SCREAMING_SNAKE_CASE__ ) ) def _a ( SCREAMING_SNAKE_CASE__ : list ) -> bool: '''simple docstring''' return len(set(SCREAMING_SNAKE_CASE__ ) ) in (0, 1) def _a ( SCREAMING_SNAKE_CASE__ : int ) -> list: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 2 while True: # Increment each value of a generated range SCREAMING_SNAKE_CASE__ : List[str] = [base + i for i in range(SCREAMING_SNAKE_CASE__ )] # Run elements through out unique_prime_factors function # Append our target number to the end. SCREAMING_SNAKE_CASE__ : Tuple = [upf_len(SCREAMING_SNAKE_CASE__ ) for x in group] checker.append(SCREAMING_SNAKE_CASE__ ) # If all numbers in the list are equal, return the group variable. if equality(SCREAMING_SNAKE_CASE__ ): return group # Increment our base variable by 1 base += 1 def _a ( SCREAMING_SNAKE_CASE__ : int = 4 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = run(SCREAMING_SNAKE_CASE__ ) return results[0] if len(SCREAMING_SNAKE_CASE__ ) else None if __name__ == "__main__": print(solution())
663
from collections.abc import Callable import numpy as np def _a ( SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = int(np.ceil((x_end - xa) / step_size ) ) SCREAMING_SNAKE_CASE__ : Tuple = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE__ : Tuple = ya SCREAMING_SNAKE_CASE__ : Dict = xa for k in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = y[k] + step_size * ode_func(SCREAMING_SNAKE_CASE__ , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
663
1
def _a ( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError("The length of profit and weight must be same." ) if max_weight <= 0: raise ValueError("max_weight must greater than zero." ) if any(p < 0 for p in profit ): raise ValueError("Profit can not be negative." ) if any(w < 0 for w in weight ): raise ValueError("Weight can not be negative." ) # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. SCREAMING_SNAKE_CASE__ : str = [p / w for p, w in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] # Creating a copy of the list and sorting profit/weight in ascending order SCREAMING_SNAKE_CASE__ : Union[str, Any] = sorted(SCREAMING_SNAKE_CASE__ ) # declaring useful variables SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight SCREAMING_SNAKE_CASE__ : Optional[Any] = sorted_profit_by_weight[length - i - 1] SCREAMING_SNAKE_CASE__ : Dict = profit_by_weight.index(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( '''Input profits, weights, and then max_weight (all positive ints) separated by ''' '''spaces.''' ) _lowerCamelCase : Tuple = [int(x) for x in input('''Input profits separated by spaces: ''').split()] _lowerCamelCase : Union[str, Any] = [int(x) for x in input('''Input weights separated by spaces: ''').split()] _lowerCamelCase : str = int(input('''Max weight allowed: ''')) # Function Call calc_profit(profit, weight, max_weight)
663
def _a ( SCREAMING_SNAKE_CASE__ : List[Any]=2_81_23 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i SCREAMING_SNAKE_CASE__ : int = set() SCREAMING_SNAKE_CASE__ : Any = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(SCREAMING_SNAKE_CASE__ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
663
1
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : str = {name: getattr(transformers, name + '''Fast''') for name in SLOW_TO_FAST_CONVERTERS} def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: '''simple docstring''' if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'''Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.''' ) if tokenizer_name is None: SCREAMING_SNAKE_CASE__ : str = TOKENIZER_CLASSES else: SCREAMING_SNAKE_CASE__ : Tuple = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + "Fast" )} logger.info(f'''Loading tokenizer classes: {tokenizer_names}''' ) for tokenizer_name in tokenizer_names: SCREAMING_SNAKE_CASE__ : Optional[Any] = TOKENIZER_CLASSES[tokenizer_name] SCREAMING_SNAKE_CASE__ : List[str] = True if checkpoint_name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [checkpoint_name] logger.info(f'''For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}''' ) for checkpoint in checkpoint_names: logger.info(f'''Loading {tokenizer_class.__class__.__name__} {checkpoint}''' ) # Load tokenizer SCREAMING_SNAKE_CASE__ : str = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'''Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}''' ) # For organization names we create sub-directories if "/" in checkpoint: SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[Any] = checkpoint.split("/" ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: SCREAMING_SNAKE_CASE__ : Optional[Any] = checkpoint SCREAMING_SNAKE_CASE__ : Optional[int] = dump_path else: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Any = dump_path logger.info(f'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: SCREAMING_SNAKE_CASE__ : int = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] SCREAMING_SNAKE_CASE__ : List[str] = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = None logger.info(f'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'''=> File names {file_names}''' ) for file_name in file_names: if not file_name.endswith("tokenizer.json" ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'''=> removing {file_name}''' ) if __name__ == "__main__": _lowerCamelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--dump_path''', default=None, type=str, required=True, help='''Path to output generated fast tokenizer files.''' ) parser.add_argument( '''--tokenizer_name''', default=None, type=str, help=( f"Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will " '''download and convert all the checkpoints from AWS.''' ), ) parser.add_argument( '''--checkpoint_name''', default=None, type=str, help='''Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.''', ) parser.add_argument( '''--force_download''', action='''store_true''', help='''Re-download checkpoints.''', ) _lowerCamelCase : Optional[Any] = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
663
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase : Optional[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = ['''MobileViTFeatureExtractor'''] _lowerCamelCase : List[str] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[Any] = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class lowerCamelCase : """simple docstring""" def __init__( self : Any, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Union[str, Any]=1_3, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : str=1_6, _UpperCAmelCase : Tuple=[1, 2, 1], _UpperCAmelCase : List[str]=[2, 2, 4], _UpperCAmelCase : Tuple=2, _UpperCAmelCase : str=2.0, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=0.0, _UpperCAmelCase : Any=0.0, _UpperCAmelCase : Optional[int]=0.1, _UpperCAmelCase : int="gelu", _UpperCAmelCase : Any=False, _UpperCAmelCase : Any=True, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Any=1E-5, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : List[Any]=None, _UpperCAmelCase : str=True, _UpperCAmelCase : Union[str, Any]=1_0, _UpperCAmelCase : List[str]=8, _UpperCAmelCase : Union[str, Any]=["stage1", "stage2", "stage3"], _UpperCAmelCase : Any=[1, 2, 3], ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = embed_dim SCREAMING_SNAKE_CASE__ : List[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = num_heads SCREAMING_SNAKE_CASE__ : str = window_size SCREAMING_SNAKE_CASE__ : Any = mlp_ratio SCREAMING_SNAKE_CASE__ : List[str] = qkv_bias SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = drop_path_rate SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Tuple = patch_norm SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : Optional[int] = use_labels SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_stride SCREAMING_SNAKE_CASE__ : List[Any] = out_features SCREAMING_SNAKE_CASE__ : Dict = out_indices def A_ ( self : List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[int] ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, out_features=self.out_features, out_indices=self.out_indices, ) def A_ ( self : Dict, _UpperCAmelCase : int, _UpperCAmelCase : str, _UpperCAmelCase : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def A_ ( self : Optional[int], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any, _UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = MaskFormerSwinBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ), len(config.out_features ) ) self.parent.assertListEqual(model.channels, [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = ["stem"] SCREAMING_SNAKE_CASE__ : str = MaskFormerSwinBackbone(config=_UpperCAmelCase ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) UpperCAmelCase_ = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = MaskFormerSwinModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = ConfigTester(self, config_class=_UpperCAmelCase, embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def A_ ( self : Any ) -> List[Any]: """simple docstring""" pass def A_ ( self : Tuple ) -> Any: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A_ ( self : int ) -> Optional[Any]: """simple docstring""" return def A_ ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_UpperCAmelCase ) @unittest.skip("Swin does not use inputs_embeds" ) def A_ ( self : Any ) -> Optional[int]: """simple docstring""" pass @unittest.skip("Swin does not support feedforward chunking" ) def A_ ( self : List[str] ) -> Optional[int]: """simple docstring""" pass def A_ ( self : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, nn.Linear ) ) def A_ ( self : Union[str, Any] ) -> List[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__ : Dict = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def A_ ( self : Dict ) -> List[str]: """simple docstring""" pass def A_ ( self : List[str], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr( self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_UpperCAmelCase ), _UpperCAmelCase ) # Swin has a different seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Dict = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Any = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def A_ ( self : List[Any] ) -> Dict: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Dict ) -> str: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" pass def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_UpperCAmelCase : Optional[Any] ): SCREAMING_SNAKE_CASE__ : Dict = 0 return t def check_equivalence(_UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : Optional[Any]={} ): with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ).to_tuple() def recursive_check(_UpperCAmelCase : int, _UpperCAmelCase : Dict ): if isinstance(_UpperCAmelCase, (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_UpperCAmelCase, _UpperCAmelCase ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif isinstance(_UpperCAmelCase, _UpperCAmelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values(), dict_object.values() ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_UpperCAmelCase ), set_nan_tensor_to_zero(_UpperCAmelCase ), atol=1E-5 ), msg=( "Tuple and dict output are not equal. Difference:" F''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' F''' {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}. Dict has''' F''' `nan`: {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}.''' ), ) recursive_check(_UpperCAmelCase, _UpperCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) @require_torch class lowerCamelCase (unittest.TestCase , __lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (MaskFormerSwinBackbone,) if is_torch_available() else () UpperCAmelCase_ = MaskFormerSwinConfig def A_ ( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModelTester(self ) def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = backbone_class(_UpperCAmelCase ) backbone.to(_UpperCAmelCase ) backbone.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps, _UpperCAmelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels ): self.assertTrue(feature_map.shape[:2], (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase, output_hidden_states=_UpperCAmelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ), len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:], backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels), (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: SCREAMING_SNAKE_CASE__ : int = backbone(**_UpperCAmelCase, output_attentions=_UpperCAmelCase ) self.assertIsNotNone(outputs.attentions )
663
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = BlenderbotSmallConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Optional[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : Optional[int]=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : List[Any]=True, _UpperCAmelCase : Union[str, Any]=False, _UpperCAmelCase : str=9_9, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Any=2, _UpperCAmelCase : Any=4, _UpperCAmelCase : List[Any]=3_7, _UpperCAmelCase : Dict=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=2_0, _UpperCAmelCase : int=2, _UpperCAmelCase : Union[str, Any]=1, _UpperCAmelCase : List[str]=0, ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = eos_token_id SCREAMING_SNAKE_CASE__ : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE__ : List[Any] = bos_token_id def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Dict = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Any = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : str = prepare_blenderbot_small_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFBlenderbotSmallModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : Optional[Any] = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : List[str] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : Tuple = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Dict = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : int = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Any = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Tuple = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : Tuple = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) UpperCAmelCase_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFBlenderbotSmallForConditionalGeneration, "feature-extraction": TFBlenderbotSmallModel, "summarization": TFBlenderbotSmallForConditionalGeneration, "text2text-generation": TFBlenderbotSmallForConditionalGeneration, "translation": TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFBlenderbotSmallModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[int] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Any ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like " " i'm going to throw up.\nand why is that?" ] UpperCAmelCase_ = "facebook/blenderbot_small-90M" @cached_property def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def A_ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
663
1
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class lowerCamelCase : """simple docstring""" def A_ ( self : Union[str, Any], _UpperCAmelCase : Optional[Any] ) -> List[str]: """simple docstring""" raise NotImplementedError() def A_ ( self : Tuple ) -> List[str]: """simple docstring""" raise NotImplementedError() class lowerCamelCase (__lowerCamelCase ): """simple docstring""" def __init__( self : List[Any], _UpperCAmelCase : "AutoTokenizer", _UpperCAmelCase : bool = False, **_UpperCAmelCase : Optional[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = tokenizer SCREAMING_SNAKE_CASE__ : str = skip_prompt SCREAMING_SNAKE_CASE__ : Union[str, Any] = decode_kwargs # variables used in the streaming process SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : int = True def A_ ( self : Optional[Any], _UpperCAmelCase : Any ) -> str: """simple docstring""" if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1" ) elif len(value.shape ) > 1: SCREAMING_SNAKE_CASE__ : int = value[0] if self.skip_prompt and self.next_tokens_are_prompt: SCREAMING_SNAKE_CASE__ : int = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) SCREAMING_SNAKE_CASE__ : int = self.tokenizer.decode(self.token_cache, **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("\n" ): SCREAMING_SNAKE_CASE__ : Any = text[self.print_len :] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = 0 # If the last token is a CJK character, we print the characters. elif len(_UpperCAmelCase ) > 0 and self._is_chinese_char(ord(text[-1] ) ): SCREAMING_SNAKE_CASE__ : List[Any] = text[self.print_len :] self.print_len += len(_UpperCAmelCase ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: SCREAMING_SNAKE_CASE__ : Dict = text[self.print_len : text.rfind(" " ) + 1] self.print_len += len(_UpperCAmelCase ) self.on_finalized_text(_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" # Flush the cache, if it exists if len(self.token_cache ) > 0: SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer.decode(self.token_cache, **self.decode_kwargs ) SCREAMING_SNAKE_CASE__ : Tuple = text[self.print_len :] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Any = 0 else: SCREAMING_SNAKE_CASE__ : List[Any] = "" SCREAMING_SNAKE_CASE__ : Union[str, Any] = True self.on_finalized_text(_UpperCAmelCase, stream_end=_UpperCAmelCase ) def A_ ( self : Dict, _UpperCAmelCase : str, _UpperCAmelCase : bool = False ) -> Optional[Any]: """simple docstring""" print(_UpperCAmelCase, flush=_UpperCAmelCase, end="" if not stream_end else None ) def A_ ( self : Any, _UpperCAmelCase : Tuple ) -> str: """simple docstring""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. 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 class lowerCamelCase (__lowerCamelCase ): """simple docstring""" def __init__( self : int, _UpperCAmelCase : "AutoTokenizer", _UpperCAmelCase : bool = False, _UpperCAmelCase : Optional[float] = None, **_UpperCAmelCase : Optional[int] ) -> List[str]: """simple docstring""" super().__init__(_UpperCAmelCase, _UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Queue() SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = timeout def A_ ( self : Dict, _UpperCAmelCase : str, _UpperCAmelCase : bool = False ) -> Union[str, Any]: """simple docstring""" self.text_queue.put(_UpperCAmelCase, timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal, timeout=self.timeout ) def __iter__( self : Union[str, Any] ) -> Tuple: """simple docstring""" return self def A_ ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
663
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (DPMSolverSDEScheduler,) UpperCAmelCase_ = 10 def A_ ( self : List[str], **_UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "noise_sampler_seed": 0, } config.update(**_UpperCAmelCase ) return config def A_ ( self : Tuple ) -> int: """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_UpperCAmelCase ) def A_ ( self : int ) -> int: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001], [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_UpperCAmelCase, beta_end=_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : int = self.dummy_model() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Union[str, Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Dict = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config(prediction_type="v_prediction" ) SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Tuple = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def A_ ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : int = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Tuple = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def A_ ( self : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Any = scheduler_class(**_UpperCAmelCase, use_karras_sigmas=_UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps, device=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_sample_deter.to(_UpperCAmelCase ) * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_UpperCAmelCase ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : str = scheduler.scale_model_input(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = scheduler.step(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = torch.sum(torch.abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.mean(torch.abs(_UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
663
1
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "EncodecFeatureExtractor" UpperCAmelCase_ = ("T5Tokenizer", "T5TokenizerFast") def __init__( self : List[Any], _UpperCAmelCase : List[str], _UpperCAmelCase : Optional[int] ) -> Any: """simple docstring""" super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self.feature_extractor SCREAMING_SNAKE_CASE__ : List[Any] = False def A_ ( self : List[str], _UpperCAmelCase : List[Any]=None, _UpperCAmelCase : str=None, _UpperCAmelCase : int=True ) -> Tuple: """simple docstring""" return self.tokenizer.get_decoder_prompt_ids(task=_UpperCAmelCase, language=_UpperCAmelCase, no_timestamps=_UpperCAmelCase ) def __call__( self : Tuple, *_UpperCAmelCase : List[Any], **_UpperCAmelCase : str ) -> List[str]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = kwargs.pop("audio", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("sampling_rate", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Any = args[0] SCREAMING_SNAKE_CASE__ : int = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if text is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if audio is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extractor(_UpperCAmelCase, *_UpperCAmelCase, sampling_rate=_UpperCAmelCase, **_UpperCAmelCase ) if audio is None: return inputs elif text is None: return audio_inputs else: SCREAMING_SNAKE_CASE__ : Optional[Any] = audio_inputs["input_values"] if "padding_mask" in audio_inputs: SCREAMING_SNAKE_CASE__ : Dict = audio_inputs["padding_mask"] return inputs def A_ ( self : Optional[Any], *_UpperCAmelCase : List[Any], **_UpperCAmelCase : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = kwargs.pop("audio", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("padding_mask", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : List[Any] = args[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = args[1:] if audio_values is not None: return self._decode_audio(_UpperCAmelCase, padding_mask=_UpperCAmelCase ) else: return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Union[str, Any], *_UpperCAmelCase : int, **_UpperCAmelCase : Optional[Any] ) -> Optional[Any]: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : Dict, _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Optional = None ) -> List[np.ndarray]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = to_numpy(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Optional[int] = audio_values.shape if padding_mask is None: return list(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = to_numpy(_UpperCAmelCase ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = seq_len - padding_mask.shape[-1] SCREAMING_SNAKE_CASE__ : List[str] = 1 - self.feature_extractor.padding_value SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.pad(_UpperCAmelCase, ((0, 0), (0, difference)), "constant", constant_values=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = audio_values.tolist() for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] SCREAMING_SNAKE_CASE__ : str = sliced_audio.reshape(_UpperCAmelCase, -1 ) return audio_values
663
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = ["image_processor", "tokenizer"] UpperCAmelCase_ = "AutoImageProcessor" UpperCAmelCase_ = "AutoTokenizer" def __init__( self : Tuple, _UpperCAmelCase : str=None, _UpperCAmelCase : str=None, **_UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead.", _UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop("feature_extractor" ) SCREAMING_SNAKE_CASE__ : Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self.image_processor SCREAMING_SNAKE_CASE__ : Any = False def __call__( self : List[str], *_UpperCAmelCase : Any, **_UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("images", _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("text", _UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = args[0] SCREAMING_SNAKE_CASE__ : str = args[1:] if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: SCREAMING_SNAKE_CASE__ : Dict = self.image_processor(_UpperCAmelCase, *_UpperCAmelCase, **_UpperCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE__ : str = self.tokenizer(_UpperCAmelCase, **_UpperCAmelCase ) if text is None: return inputs elif images is None: return encodings else: SCREAMING_SNAKE_CASE__ : Optional[int] = encodings["input_ids"] return inputs def A_ ( self : Dict, *_UpperCAmelCase : Tuple, **_UpperCAmelCase : Dict ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*_UpperCAmelCase, **_UpperCAmelCase ) def A_ ( self : List[str], *_UpperCAmelCase : int, **_UpperCAmelCase : Dict ) -> Any: """simple docstring""" return self.tokenizer.decode(*_UpperCAmelCase, **_UpperCAmelCase ) @contextmanager def A_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your images inputs, or in a separate call." ) SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False def A_ ( self : Tuple, _UpperCAmelCase : List[Any], _UpperCAmelCase : int=False, _UpperCAmelCase : Optional[Any]=None ) -> Any: """simple docstring""" if added_vocab is None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer.get_added_vocab() SCREAMING_SNAKE_CASE__ : str = {} while tokens: SCREAMING_SNAKE_CASE__ : Dict = re.search(r"<s_(.*?)>", _UpperCAmelCase, re.IGNORECASE ) if start_token is None: break SCREAMING_SNAKE_CASE__ : Any = start_token.group(1 ) SCREAMING_SNAKE_CASE__ : Dict = re.search(rF'''</s_{key}>''', _UpperCAmelCase, re.IGNORECASE ) SCREAMING_SNAKE_CASE__ : Any = start_token.group() if end_token is None: SCREAMING_SNAKE_CASE__ : List[str] = tokens.replace(_UpperCAmelCase, "" ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = end_token.group() SCREAMING_SNAKE_CASE__ : List[str] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = re.escape(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}''', _UpperCAmelCase, re.IGNORECASE ) if content is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node SCREAMING_SNAKE_CASE__ : str = self.tokenajson(_UpperCAmelCase, is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if value: if len(_UpperCAmelCase ) == 1: SCREAMING_SNAKE_CASE__ : str = value[0] SCREAMING_SNAKE_CASE__ : List[str] = value else: # leaf nodes SCREAMING_SNAKE_CASE__ : Optional[int] = [] for leaf in content.split(r"<sep/>" ): SCREAMING_SNAKE_CASE__ : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": SCREAMING_SNAKE_CASE__ : str = leaf[1:-2] # for categorical special tokens output[key].append(_UpperCAmelCase ) if len(output[key] ) == 1: SCREAMING_SNAKE_CASE__ : str = output[key][0] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokens[tokens.find(_UpperCAmelCase ) + len(_UpperCAmelCase ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=_UpperCAmelCase, added_vocab=_UpperCAmelCase ) if len(_UpperCAmelCase ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def A_ ( self : str ) -> Optional[Any]: """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.", _UpperCAmelCase, ) return self.image_processor_class @property def A_ ( self : int ) -> List[str]: """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.", _UpperCAmelCase, ) return self.image_processor
663
1
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 _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) @dataclass class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = [ "no_inference", "no_cuda", "no_tpu", "no_speed", "no_memory", "no_env_print", "no_multi_process", ] def __init__( self : str, **_UpperCAmelCase : List[Any] ) -> Dict: """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: SCREAMING_SNAKE_CASE__ : Optional[int] = deprecated_arg[3:] SCREAMING_SNAKE_CASE__ : Dict = not kwargs.pop(_UpperCAmelCase ) logger.warning( F'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' F''' {positive_arg}={kwargs[positive_arg]}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = kwargs.pop("tpu_name", self.tpu_name ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("device_idx", self.device_idx ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("eager_mode", self.eager_mode ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop("use_xla", self.use_xla ) super().__init__(**_UpperCAmelCase ) UpperCAmelCase_ = field( default=__lowerCamelCase , metadata={"help": "Name of TPU"} , ) UpperCAmelCase_ = field( default=0 , metadata={"help": "CPU / GPU device index. Defaults to 0."} , ) UpperCAmelCase_ = field(default=__lowerCamelCase , metadata={"help": "Benchmark models in eager model."} ) UpperCAmelCase_ = field( default=__lowerCamelCase , metadata={ "help": "Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`." } , ) @cached_property def A_ ( self : Union[str, Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: """simple docstring""" requires_backends(self, ["tf"] ) SCREAMING_SNAKE_CASE__ : int = None if self.tpu: try: if self.tpu_name: SCREAMING_SNAKE_CASE__ : Any = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: SCREAMING_SNAKE_CASE__ : Dict = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: SCREAMING_SNAKE_CASE__ : List[Any] = None return tpu @cached_property def A_ ( self : str ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: """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 ) SCREAMING_SNAKE_CASE__ : Any = 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" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.distribute.OneDeviceStrategy(device=F'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([], "GPU" ) # disable GPU SCREAMING_SNAKE_CASE__ : Tuple = tf.distribute.OneDeviceStrategy(device=F'''/cpu:{self.device_idx}''' ) return strategy @property def A_ ( self : List[Any] ) -> bool: """simple docstring""" requires_backends(self, ["tf"] ) return self._setup_tpu is not None @property def A_ ( self : Dict ) -> "tf.distribute.Strategy": """simple docstring""" requires_backends(self, ["tf"] ) return self._setup_strategy @property def A_ ( self : Tuple ) -> List[str]: """simple docstring""" requires_backends(self, ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def A_ ( self : Optional[int] ) -> int: """simple docstring""" requires_backends(self, ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def A_ ( self : Any ) -> bool: """simple docstring""" return self.n_gpu > 0
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _lowerCamelCase : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = ['''BartphoTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ) -> int: '''simple docstring''' def update_area_of_max_square(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 SCREAMING_SNAKE_CASE__ : Tuple = update_area_of_max_square(SCREAMING_SNAKE_CASE__ , col + 1 ) SCREAMING_SNAKE_CASE__ : Tuple = update_area_of_max_square(row + 1 , col + 1 ) SCREAMING_SNAKE_CASE__ : List[Any] = update_area_of_max_square(row + 1 , SCREAMING_SNAKE_CASE__ ) if mat[row][col]: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 + min([right, diagonal, down] ) SCREAMING_SNAKE_CASE__ : Optional[int] = max(largest_square_area[0] , SCREAMING_SNAKE_CASE__ ) return sub_problem_sol else: return 0 SCREAMING_SNAKE_CASE__ : int = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ) -> int: '''simple docstring''' def update_area_of_max_square_using_dp_array( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] SCREAMING_SNAKE_CASE__ : List[str] = update_area_of_max_square_using_dp_array(SCREAMING_SNAKE_CASE__ , col + 1 , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = update_area_of_max_square_using_dp_array(row + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if mat[row][col]: SCREAMING_SNAKE_CASE__ : Any = 1 + min([right, diagonal, down] ) SCREAMING_SNAKE_CASE__ : Any = max(largest_square_area[0] , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = sub_problem_sol return sub_problem_sol else: return 0 SCREAMING_SNAKE_CASE__ : str = [0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[-1] * cols for _ in range(SCREAMING_SNAKE_CASE__ )] update_area_of_max_square_using_dp_array(0 , 0 , SCREAMING_SNAKE_CASE__ ) return largest_square_area[0] def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [[0] * (cols + 1) for _ in range(rows + 1 )] SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): SCREAMING_SNAKE_CASE__ : Tuple = dp_array[row][col + 1] SCREAMING_SNAKE_CASE__ : str = dp_array[row + 1][col + 1] SCREAMING_SNAKE_CASE__ : int = dp_array[row + 1][col] if mat[row][col] == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 + min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = max(dp_array[row][col] , SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = 0 return largest_square_area def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [0] * (cols + 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0] * (cols + 1) SCREAMING_SNAKE_CASE__ : int = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = current_row[col + 1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = next_row[col + 1] SCREAMING_SNAKE_CASE__ : List[Any] = next_row[col] if mat[row][col] == 1: SCREAMING_SNAKE_CASE__ : Tuple = 1 + min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[str] = max(current_row[col] , SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : int = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
663
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class lowerCamelCase : """simple docstring""" def __init__( self : Any, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Union[str, Any]=1_3, _UpperCAmelCase : Union[str, Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : str=1_6, _UpperCAmelCase : Tuple=[1, 2, 1], _UpperCAmelCase : List[str]=[2, 2, 4], _UpperCAmelCase : Tuple=2, _UpperCAmelCase : str=2.0, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=0.0, _UpperCAmelCase : Any=0.0, _UpperCAmelCase : Optional[int]=0.1, _UpperCAmelCase : int="gelu", _UpperCAmelCase : Any=False, _UpperCAmelCase : Any=True, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Any=1E-5, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : List[Any]=None, _UpperCAmelCase : str=True, _UpperCAmelCase : Union[str, Any]=1_0, _UpperCAmelCase : List[str]=8, _UpperCAmelCase : Union[str, Any]=["stage1", "stage2", "stage3"], _UpperCAmelCase : Any=[1, 2, 3], ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = embed_dim SCREAMING_SNAKE_CASE__ : List[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = num_heads SCREAMING_SNAKE_CASE__ : str = window_size SCREAMING_SNAKE_CASE__ : Any = mlp_ratio SCREAMING_SNAKE_CASE__ : List[str] = qkv_bias SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = drop_path_rate SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Tuple = patch_norm SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : Optional[int] = use_labels SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_stride SCREAMING_SNAKE_CASE__ : List[Any] = out_features SCREAMING_SNAKE_CASE__ : Dict = out_indices def A_ ( self : List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[int] ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, out_features=self.out_features, out_indices=self.out_indices, ) def A_ ( self : Dict, _UpperCAmelCase : int, _UpperCAmelCase : str, _UpperCAmelCase : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def A_ ( self : Optional[int], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Any, _UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = MaskFormerSwinBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ), len(config.out_features ) ) self.parent.assertListEqual(model.channels, [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = ["stem"] SCREAMING_SNAKE_CASE__ : str = MaskFormerSwinBackbone(config=_UpperCAmelCase ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) UpperCAmelCase_ = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = MaskFormerSwinModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = ConfigTester(self, config_class=_UpperCAmelCase, embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def A_ ( self : Any ) -> List[Any]: """simple docstring""" pass def A_ ( self : Tuple ) -> Any: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A_ ( self : int ) -> Optional[Any]: """simple docstring""" return def A_ ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_UpperCAmelCase ) @unittest.skip("Swin does not use inputs_embeds" ) def A_ ( self : Any ) -> Optional[int]: """simple docstring""" pass @unittest.skip("Swin does not support feedforward chunking" ) def A_ ( self : List[str] ) -> Optional[int]: """simple docstring""" pass def A_ ( self : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, nn.Linear ) ) def A_ ( self : Union[str, Any] ) -> List[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__ : Dict = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def A_ ( self : Dict ) -> List[str]: """simple docstring""" pass def A_ ( self : List[str], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr( self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_UpperCAmelCase ), _UpperCAmelCase ) # Swin has a different seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def A_ ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : Dict = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Any = True self.check_hidden_states_output(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def A_ ( self : List[Any] ) -> Dict: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Dict ) -> str: """simple docstring""" pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" pass def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_UpperCAmelCase : Optional[Any] ): SCREAMING_SNAKE_CASE__ : Dict = 0 return t def check_equivalence(_UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : Optional[Any]={} ): with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = model(**_UpperCAmelCase, return_dict=_UpperCAmelCase, **_UpperCAmelCase ).to_tuple() def recursive_check(_UpperCAmelCase : int, _UpperCAmelCase : Dict ): if isinstance(_UpperCAmelCase, (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_UpperCAmelCase, _UpperCAmelCase ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif isinstance(_UpperCAmelCase, _UpperCAmelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values(), dict_object.values() ): recursive_check(_UpperCAmelCase, _UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_UpperCAmelCase ), set_nan_tensor_to_zero(_UpperCAmelCase ), atol=1E-5 ), msg=( "Tuple and dict output are not equal. Difference:" F''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' F''' {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}. Dict has''' F''' `nan`: {torch.isnan(_UpperCAmelCase ).any()} and `inf`: {torch.isinf(_UpperCAmelCase )}.''' ), ) recursive_check(_UpperCAmelCase, _UpperCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(_UpperCAmelCase, _UpperCAmelCase, return_labels=_UpperCAmelCase ) check_equivalence(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, {"output_hidden_states": True} ) @require_torch class lowerCamelCase (unittest.TestCase , __lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = (MaskFormerSwinBackbone,) if is_torch_available() else () UpperCAmelCase_ = MaskFormerSwinConfig def A_ ( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MaskFormerSwinModelTester(self ) def A_ ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = backbone_class(_UpperCAmelCase ) backbone.to(_UpperCAmelCase ) backbone.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps, _UpperCAmelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels ): self.assertTrue(feature_map.shape[:2], (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True SCREAMING_SNAKE_CASE__ : Optional[int] = backbone(**_UpperCAmelCase, output_hidden_states=_UpperCAmelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ), len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:], backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels), (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: SCREAMING_SNAKE_CASE__ : int = backbone(**_UpperCAmelCase, output_attentions=_UpperCAmelCase ) self.assertIsNotNone(outputs.attentions )
663
1
def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: '''simple docstring''' print("\nThe shortest path matrix using Floyd Warshall algorithm\n" ) for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): if dist[i][j] != float("inf" ): print(int(dist[i][j] ) , end="\t" ) else: print("INF" , end="\t" ) print() def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [[float("inf" ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ )] for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(SCREAMING_SNAKE_CASE__ ): # looping through rows of graph array for i in range(SCREAMING_SNAKE_CASE__ ): # looping through columns of graph array for j in range(SCREAMING_SNAKE_CASE__ ): if ( dist[i][k] != float("inf" ) and dist[k][j] != float("inf" ) and dist[i][k] + dist[k][j] < dist[i][j] ): SCREAMING_SNAKE_CASE__ : int = dist[i][k] + dist[k][j] _print_dist(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return dist, v if __name__ == "__main__": _lowerCamelCase : Optional[Any] = int(input('''Enter number of vertices: ''')) _lowerCamelCase : Optional[Any] = int(input('''Enter number of edges: ''')) _lowerCamelCase : Dict = [[float('''inf''') for i in range(v)] for j in range(v)] for i in range(v): _lowerCamelCase : Tuple = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('''\nEdge ''', i + 1) _lowerCamelCase : Optional[int] = int(input('''Enter source:''')) _lowerCamelCase : Optional[int] = int(input('''Enter destination:''')) _lowerCamelCase : Union[str, Any] = float(input('''Enter weight:''')) _lowerCamelCase : Tuple = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
663
from ....configuration_utils import PretrainedConfig from ....utils import logging _lowerCamelCase : Any = logging.get_logger(__name__) # TODO: upload to AWS _lowerCamelCase : str = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json''' ), } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "retribert" def __init__( self : Optional[Any], _UpperCAmelCase : Dict=3_0_5_2_2, _UpperCAmelCase : List[str]=7_6_8, _UpperCAmelCase : Tuple=8, _UpperCAmelCase : Optional[Any]=1_2, _UpperCAmelCase : Union[str, Any]=3_0_7_2, _UpperCAmelCase : Dict="gelu", _UpperCAmelCase : Tuple=0.1, _UpperCAmelCase : str=0.1, _UpperCAmelCase : List[str]=5_1_2, _UpperCAmelCase : Optional[int]=2, _UpperCAmelCase : Dict=0.02, _UpperCAmelCase : Any=1E-12, _UpperCAmelCase : Dict=True, _UpperCAmelCase : Any=1_2_8, _UpperCAmelCase : int=0, **_UpperCAmelCase : List[str], ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = share_encoders SCREAMING_SNAKE_CASE__ : int = projection_dim
663
1
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency _lowerCamelCase : Dict = { '''E''': 12.70, '''T''': 9.06, '''A''': 8.17, '''O''': 7.51, '''I''': 6.97, '''N''': 6.75, '''S''': 6.33, '''H''': 6.09, '''R''': 5.99, '''D''': 4.25, '''L''': 4.03, '''C''': 2.78, '''U''': 2.76, '''M''': 2.41, '''W''': 2.36, '''F''': 2.23, '''G''': 2.02, '''Y''': 1.97, '''P''': 1.93, '''B''': 1.29, '''V''': 0.98, '''K''': 0.77, '''J''': 0.15, '''X''': 0.15, '''Q''': 0.10, '''Z''': 0.07, } _lowerCamelCase : List[Any] = '''ETAOINSHRDLCUMWFGYPBVKJXQZ''' _lowerCamelCase : int = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def _a ( SCREAMING_SNAKE_CASE__ : str ) -> dict[str, int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def _a ( SCREAMING_SNAKE_CASE__ : tuple ) -> str: '''simple docstring''' return x[0] def _a ( SCREAMING_SNAKE_CASE__ : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = get_letter_count(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = "".join(freq_to_letter[freq] ) SCREAMING_SNAKE_CASE__ : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=SCREAMING_SNAKE_CASE__ , reverse=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(SCREAMING_SNAKE_CASE__ ) def _a ( SCREAMING_SNAKE_CASE__ : str ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = get_frequency_order(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
663
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin _lowerCamelCase : int = False @skip_mps class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = StableDiffusionAttendAndExcitePipeline UpperCAmelCase_ = False UpperCAmelCase_ = TEXT_TO_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"} ) UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def A_ ( cls : str ) -> Union[str, Any]: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : Tuple ) -> str: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : Any ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4), layers_per_block=1, sample_size=3_2, in_channels=4, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=3_2, attention_head_dim=(2, 4), use_linear_projection=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=_UpperCAmelCase, set_alpha_to_one=_UpperCAmelCase, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = AutoencoderKL( block_out_channels=[3_2, 6_4], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, sample_size=1_2_8, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=3_2, intermediate_size=3_7, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, hidden_act="gelu", projection_dim=5_1_2, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTextModel(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def A_ ( self : Optional[Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Any=0 ) -> Optional[Any]: """simple docstring""" if str(_UpperCAmelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE__ : Tuple = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = { "prompt": "a cat and a frog", "token_indices": [2, 5], "generator": generator, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", "max_iter_to_alter": 2, "thresholds": {0: 0.7}, } return inputs def A_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = "cpu" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.pipeline_class(**_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_dummy_inputs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = pipe(**_UpperCAmelCase ).images SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 6_4, 6_4, 3) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) SCREAMING_SNAKE_CASE__ : Dict = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_UpperCAmelCase, 1E-3 ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def A_ ( self : Any ) -> str: """simple docstring""" # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : Optional[Any] ) -> str: """simple docstring""" self._test_inference_batch_single_identical(batch_size=2, expected_max_diff=7E-4 ) def A_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def A_ ( self : Any ) -> List[str]: """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" super().test_save_load_local(expected_max_difference=5E-4 ) def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class lowerCamelCase (unittest.TestCase ): """simple docstring""" @classmethod def A_ ( cls : Union[str, Any] ) -> Tuple: """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) @classmethod def A_ ( cls : List[str] ) -> List[str]: """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(_UpperCAmelCase ) def A_ ( self : str ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(5_1 ) SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionAttendAndExcitePipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=_UpperCAmelCase, torch_dtype=torch.floataa ) pipe.to("cuda" ) SCREAMING_SNAKE_CASE__ : List[str] = "a painting of an elephant with glasses" SCREAMING_SNAKE_CASE__ : Optional[int] = [5, 7] SCREAMING_SNAKE_CASE__ : str = pipe( prompt=_UpperCAmelCase, token_indices=_UpperCAmelCase, guidance_scale=7.5, generator=_UpperCAmelCase, num_inference_steps=5, max_iter_to_alter=5, output_type="numpy", ).images[0] SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy" ) assert np.abs((expected_image - image).max() ) < 5E-1
663
1
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCamelCase : """simple docstring""" def __init__( self : int, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[int]=1_3, _UpperCAmelCase : Tuple=3_0, _UpperCAmelCase : Tuple=2, _UpperCAmelCase : Tuple=3, _UpperCAmelCase : Optional[Any]=True, _UpperCAmelCase : Optional[Any]=True, _UpperCAmelCase : Optional[int]=3_2, _UpperCAmelCase : Any=2, _UpperCAmelCase : Optional[Any]=4, _UpperCAmelCase : int=3_7, _UpperCAmelCase : Optional[Any]="gelu", _UpperCAmelCase : List[Any]=0.1, _UpperCAmelCase : str=0.1, _UpperCAmelCase : int=1_0, _UpperCAmelCase : Dict=0.02, _UpperCAmelCase : List[str]=3, _UpperCAmelCase : List[str]=None, ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : int = patch_size SCREAMING_SNAKE_CASE__ : int = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Optional[int] = use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = num_patches + 1 def A_ ( self : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[int] ) -> List[Any]: """simple docstring""" return ViTConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=_UpperCAmelCase, initializer_range=self.initializer_range, ) def A_ ( self : Optional[Any], _UpperCAmelCase : List[str], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = TFViTModel(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = model(_UpperCAmelCase, training=_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. SCREAMING_SNAKE_CASE__ : Dict = self.image_size // 2 SCREAMING_SNAKE_CASE__ : Any = pixel_values[:, :, :image_size, :image_size] SCREAMING_SNAKE_CASE__ : List[str] = model(_UpperCAmelCase, interpolate_pos_encoding=_UpperCAmelCase, training=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, seq_length, self.hidden_size) ) def A_ ( self : Any, _UpperCAmelCase : List[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = TFViTForImageClassification(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = model(_UpperCAmelCase, labels=_UpperCAmelCase, training=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_size // 2 SCREAMING_SNAKE_CASE__ : Dict = pixel_values[:, :, :image_size, :image_size] SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase, interpolate_pos_encoding=_UpperCAmelCase, training=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : List[Any] = TFViTForImageClassification(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () UpperCAmelCase_ = ( {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification} if is_tf_available() else {} ) UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = TFViTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self, config_class=_UpperCAmelCase, has_text_modality=_UpperCAmelCase, hidden_size=3_7 ) def A_ ( self : str ) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def A_ ( self : Dict ) -> List[str]: """simple docstring""" pass @unittest.skip(reason="ViT does not use inputs_embeds" ) def A_ ( self : Optional[int] ) -> Tuple: """simple docstring""" pass def A_ ( self : Dict ) -> Any: """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: SCREAMING_SNAKE_CASE__ : Optional[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (tf.keras.layers.Layer) ) SCREAMING_SNAKE_CASE__ : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, tf.keras.layers.Layer ) ) def A_ ( self : Optional[Any] ) -> Optional[int]: """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: SCREAMING_SNAKE_CASE__ : Any = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) def A_ ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def A_ ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFViTModel.from_pretrained("google/vit-base-patch16-224" ) self.assertIsNotNone(_UpperCAmelCase ) def _a ( ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class lowerCamelCase (unittest.TestCase ): """simple docstring""" @cached_property def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def A_ ( self : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ) SCREAMING_SNAKE_CASE__ : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple = prepare_img() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(images=_UpperCAmelCase, return_tensors="tf" ) # forward pass SCREAMING_SNAKE_CASE__ : int = model(**_UpperCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE__ : Tuple = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.2744, 0.8215, -0.0836] ) tf.debugging.assert_near(outputs.logits[0, :3], _UpperCAmelCase, atol=1E-4 )
663
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class lowerCamelCase : """simple docstring""" UpperCAmelCase_ = PegasusConfig UpperCAmelCase_ = {} UpperCAmelCase_ = "gelu" def __init__( self : Union[str, Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Tuple=1_3, _UpperCAmelCase : int=7, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : int=False, _UpperCAmelCase : Union[str, Any]=9_9, _UpperCAmelCase : Optional[Any]=3_2, _UpperCAmelCase : Optional[Any]=2, _UpperCAmelCase : Tuple=4, _UpperCAmelCase : str=3_7, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : Dict=4_0, _UpperCAmelCase : Any=2, _UpperCAmelCase : int=1, _UpperCAmelCase : str=0, ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : str = eos_token_id SCREAMING_SNAKE_CASE__ : Dict = pad_token_id SCREAMING_SNAKE_CASE__ : Tuple = bos_token_id def A_ ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat([input_ids, eos_tensor], axis=1 ) SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config_cls( vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_pegasus_inputs_dict(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) return config, inputs_dict def A_ ( self : Union[str, Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFPegasusModel(config=_UpperCAmelCase ).get_decoder() SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE__ : str = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["head_mask"] SCREAMING_SNAKE_CASE__ : int = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, head_mask=_UpperCAmelCase, use_cache=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : int = ids_tensor((self.batch_size, 3), config.vocab_size ) SCREAMING_SNAKE_CASE__ : str = tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([input_ids, next_tokens], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask], axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = model(_UpperCAmelCase, attention_mask=_UpperCAmelCase, past_key_values=_UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ : Optional[Any] = int(ids_tensor((1,), output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_UpperCAmelCase, _UpperCAmelCase, rtol=1E-3 ) def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : List[str]=None , ) -> Any: '''simple docstring''' if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase_ = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase_ = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFPegasusModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self, config_class=_UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase ) @require_sentencepiece @require_tokenizers @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] UpperCAmelCase_ = [ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to" " reduce the risk of wildfires.", "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.", ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase_ = "google/pegasus-xsum" @cached_property def A_ ( self : Union[str, Any] ) -> int: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def A_ ( self : str, **_UpperCAmelCase : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.translate_src_text(**_UpperCAmelCase ) assert self.expected_text == generated_words def A_ ( self : Any, **_UpperCAmelCase : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.src_text, **_UpperCAmelCase, padding=_UpperCAmelCase, return_tensors="tf" ) SCREAMING_SNAKE_CASE__ : List[str] = self.model.generate( model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_UpperCAmelCase ) return generated_words @slow def A_ ( self : List[Any] ) -> Any: """simple docstring""" self._assert_generated_batch_equal_expected()
663
1
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = CpmAntTokenizer UpperCAmelCase_ = False def A_ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : Optional[int] = [ "<d>", "</d>", "<s>", "</s>", "</_>", "<unk>", "<pad>", "</n>", "我", "是", "C", "P", "M", "A", "n", "t", ] SCREAMING_SNAKE_CASE__ : Dict = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file, "w", encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) @tooslow def A_ ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b" ) SCREAMING_SNAKE_CASE__ : List[Any] = "今天天气真好!" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["今天", "天气", "真", "好", "!"] SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = "今天天气真好!" SCREAMING_SNAKE_CASE__ : str = [tokenizer.bos_token] + tokens SCREAMING_SNAKE_CASE__ : Tuple = [6, 9_8_0_2, 1_4_9_6_2, 2_0_8_2, 8_3_1, 2_4_4] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ), _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.decode(_UpperCAmelCase ) self.assertEqual(_UpperCAmelCase, _UpperCAmelCase )
663
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase : List[str] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
663
1
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class lowerCamelCase (unittest.TestCase ): """simple docstring""" def __init__( self : List[Any], _UpperCAmelCase : int, _UpperCAmelCase : Optional[Any]=7, _UpperCAmelCase : Union[str, Any]=3, _UpperCAmelCase : Optional[Any]=1_8, _UpperCAmelCase : Tuple=3_0, _UpperCAmelCase : Tuple=4_0_0, _UpperCAmelCase : Dict=True, _UpperCAmelCase : Dict=None, _UpperCAmelCase : int=True, ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = size if size is not None else {"height": 1_8, "width": 1_8} SCREAMING_SNAKE_CASE__ : Tuple = parent SCREAMING_SNAKE_CASE__ : List[str] = batch_size SCREAMING_SNAKE_CASE__ : int = num_channels SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Dict = min_resolution SCREAMING_SNAKE_CASE__ : List[str] = max_resolution SCREAMING_SNAKE_CASE__ : Optional[Any] = do_resize SCREAMING_SNAKE_CASE__ : Optional[int] = size SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize def A_ ( self : Union[str, Any] ) -> str: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866443634033203, 0.6618829369544983, 0.3891746401786804], [-0.6042559146881104, -0.02295008860528469, 0.5423797369003296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class lowerCamelCase (__lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ImageGPTImageProcessor if is_vision_available() else None def A_ ( self : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ImageGPTImageProcessingTester(self ) @property def A_ ( self : List[Any] ) -> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def A_ ( self : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_UpperCAmelCase, "clusters" ) ) self.assertTrue(hasattr(_UpperCAmelCase, "do_resize" ) ) self.assertTrue(hasattr(_UpperCAmelCase, "size" ) ) self.assertTrue(hasattr(_UpperCAmelCase, "do_normalize" ) ) def A_ ( self : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {"height": 1_8, "width": 1_8} ) SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class.from_dict(self.image_processor_dict, size=4_2 ) self.assertEqual(image_processor.size, {"height": 4_2, "width": 4_2} ) def A_ ( self : Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(_UpperCAmelCase, obj[key] ) ) else: self.assertEqual(obj[key], _UpperCAmelCase ) def A_ ( self : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_UpperCAmelCase, "image_processor.json" ) image_processor_first.to_json_file(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processing_class.from_json_file(_UpperCAmelCase ).to_dict() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_UpperCAmelCase, image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key], _UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class.from_pretrained(_UpperCAmelCase ).to_dict() SCREAMING_SNAKE_CASE__ : Tuple = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_UpperCAmelCase, image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key], _UpperCAmelCase ) @unittest.skip("ImageGPT requires clusters at initialization" ) def A_ ( self : List[Any] ) -> Tuple: """simple docstring""" pass def _a ( ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = load_dataset("hf-internal-testing/fixtures_image_utils" , split="test" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.open(dataset[4]["file"] ) SCREAMING_SNAKE_CASE__ : int = Image.open(dataset[5]["file"] ) SCREAMING_SNAKE_CASE__ : Dict = [imagea, imagea] return images @require_vision @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" @slow def A_ ( self : List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small" ) SCREAMING_SNAKE_CASE__ : Dict = prepare_images() # test non-batched SCREAMING_SNAKE_CASE__ : List[str] = image_processing(images[0], return_tensors="pt" ) self.assertIsInstance(encoding.input_ids, torch.LongTensor ) self.assertEqual(encoding.input_ids.shape, (1, 1_0_2_4) ) SCREAMING_SNAKE_CASE__ : int = [3_0_6, 1_9_1, 1_9_1] self.assertEqual(encoding.input_ids[0, :3].tolist(), _UpperCAmelCase ) # test batched SCREAMING_SNAKE_CASE__ : Optional[int] = image_processing(_UpperCAmelCase, return_tensors="pt" ) self.assertIsInstance(encoding.input_ids, torch.LongTensor ) self.assertEqual(encoding.input_ids.shape, (2, 1_0_2_4) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [3_0_3, 1_3, 1_3] self.assertEqual(encoding.input_ids[1, -3:].tolist(), _UpperCAmelCase )
663
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = '''Hello world! cécé herlolip''' def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = FairseqRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) roberta.eval() # disable dropout SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.sentence_encoder SCREAMING_SNAKE_CASE__ : List[str] = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaXLForSequenceClassification(SCREAMING_SNAKE_CASE__ ) if classification_head else XLMRobertaXLForMaskedLM(SCREAMING_SNAKE_CASE__ ) model.eval() # Now let's copy all the weights. # Embeddings SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.embed_tokens.weight SCREAMING_SNAKE_CASE__ : str = roberta_sent_encoder.embed_positions.weight SCREAMING_SNAKE_CASE__ : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. SCREAMING_SNAKE_CASE__ : Any = roberta_sent_encoder.layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer SCREAMING_SNAKE_CASE__ : BertLayer = model.roberta.encoder.layer[i] SCREAMING_SNAKE_CASE__ : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] SCREAMING_SNAKE_CASE__ : RobertaAttention = layer.attention SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn_layer_norm.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn_layer_norm.bias # self attention SCREAMING_SNAKE_CASE__ : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = roberta_layer.self_attn.q_proj.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.self_attn.q_proj.bias SCREAMING_SNAKE_CASE__ : Any = roberta_layer.self_attn.k_proj.weight SCREAMING_SNAKE_CASE__ : int = roberta_layer.self_attn.k_proj.bias SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.self_attn.v_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.self_attn.v_proj.bias # self-attention output SCREAMING_SNAKE_CASE__ : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.weight SCREAMING_SNAKE_CASE__ : str = roberta_layer.self_attn.out_proj.bias # this one is final layer norm SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.weight SCREAMING_SNAKE_CASE__ : Dict = roberta_layer.final_layer_norm.bias # intermediate SCREAMING_SNAKE_CASE__ : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : List[Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.bias # output SCREAMING_SNAKE_CASE__ : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta_layer.fca.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta_layer.fca.bias # end of layer if classification_head: SCREAMING_SNAKE_CASE__ : str = roberta.model.classification_heads["mnli"].dense.weight SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"].dense.bias SCREAMING_SNAKE_CASE__ : int = roberta.model.classification_heads["mnli"].out_proj.weight SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head SCREAMING_SNAKE_CASE__ : Tuple = roberta.model.encoder.lm_head.dense.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.dense.bias SCREAMING_SNAKE_CASE__ : List[str] = roberta.model.encoder.lm_head.layer_norm.weight SCREAMING_SNAKE_CASE__ : Union[str, Any] = roberta.model.encoder.lm_head.layer_norm.bias SCREAMING_SNAKE_CASE__ : Optional[Any] = roberta.model.encoder.lm_head.weight SCREAMING_SNAKE_CASE__ : List[Any] = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. SCREAMING_SNAKE_CASE__ : torch.Tensor = roberta.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) # batch of size 1 SCREAMING_SNAKE_CASE__ : int = model(SCREAMING_SNAKE_CASE__ )[0] if classification_head: SCREAMING_SNAKE_CASE__ : Any = roberta.model.classification_heads["mnli"](roberta.extract_features(SCREAMING_SNAKE_CASE__ ) ) else: SCREAMING_SNAKE_CASE__ : int = roberta.model(SCREAMING_SNAKE_CASE__ )[0] print(our_output.shape , their_output.shape ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(f'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 SCREAMING_SNAKE_CASE__ : int = torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(SCREAMING_SNAKE_CASE__ ).mkdir(parents=SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_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.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) _lowerCamelCase : Any = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
663
1