code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
61
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
0
'''simple docstring''' import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowerCAmelCase_ : Optional[Any] = 'platform' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def _lowerCamelCase ( lowercase : int , lowercase : Any , lowercase : Optional[Any]=None , lowercase : Tuple=None , lowercase : List[str]=None , lowercase : int=None , lowercase : List[str]=None , lowercase : str=None , ) -> Optional[Any]: if attention_mask is None: _a = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: _a = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: _a = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _a = np.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": attention_mask, } class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Optional[Any] , __a : Tuple , __a : Optional[int]=13 , __a : Any=7 , __a : Optional[int]=True , __a : Any=False , __a : Optional[int]=99 , __a : Dict=16 , __a : Optional[Any]=2 , __a : Dict=4 , __a : List[Any]=4 , __a : Optional[Any]="gelu" , __a : Any=0.1 , __a : Optional[Any]=0.1 , __a : Dict=32 , __a : Optional[Any]=2 , __a : Optional[Any]=1 , __a : Tuple=0 , __a : Optional[int]=0.02 , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = eos_token_id _a = pad_token_id _a = bos_token_id _a = initializer_range def UpperCamelCase__ ( self : Dict ): _a = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) _a = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) _a = shift_tokens_right(__a , 1 , 2 ) _a = BlenderbotConfig( 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=__a , ) _a = prepare_blenderbot_inputs_dict(__a , __a , __a ) return config, inputs_dict def UpperCamelCase__ ( self : int ): _a , _a = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase__ ( self : List[Any] , __a : int , __a : Any , __a : int ): _a = 20 _a = model_class_name(__a ) _a = model.encode(inputs_dict["input_ids"] ) _a , _a = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) _a = model.init_cache(decoder_input_ids.shape[0] , __a , __a ) _a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) _a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _a = model.decode( decoder_input_ids[:, :-1] , __a , decoder_attention_mask=__a , past_key_values=__a , decoder_position_ids=__a , ) _a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) _a = model.decode( decoder_input_ids[:, -1:] , __a , decoder_attention_mask=__a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__a , ) _a = model.decode(__a , __a ) _a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) def UpperCamelCase__ ( self : Any , __a : int , __a : Optional[int] , __a : Dict ): _a = 20 _a = model_class_name(__a ) _a = model.encode(inputs_dict["input_ids"] ) _a , _a = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) _a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) _a = model.init_cache(decoder_input_ids.shape[0] , __a , __a ) _a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _a = model.decode( decoder_input_ids[:, :-1] , __a , decoder_attention_mask=__a , past_key_values=__a , decoder_position_ids=__a , ) _a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) _a = model.decode( decoder_input_ids[:, -1:] , __a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__a , decoder_position_ids=__a , ) _a = model.decode(__a , __a , decoder_attention_mask=__a ) _a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) @require_flax class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" __a =99 def UpperCamelCase__ ( self : Union[str, Any] ): _a = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) _a = input_ids.shape[0] _a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def UpperCamelCase__ ( self : Union[str, Any] ): _a , _a , _a = self._get_config_and_data() _a = FlaxBlenderbotForConditionalGeneration(__a ) _a = lm_model(input_ids=__a ) _a = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["logits"].shape , __a ) def UpperCamelCase__ ( self : List[str] ): _a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) _a = FlaxBlenderbotForConditionalGeneration(__a ) _a = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) _a = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) _a = lm_model(input_ids=__a , decoder_input_ids=__a ) _a = (*summary.shape, config.vocab_size) self.assertEqual(outputs["logits"].shape , __a ) def UpperCamelCase__ ( self : Tuple ): _a = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) _a = shift_tokens_right(__a , 1 , 2 ) _a = np.equal(__a , 1 ).astype(np.floataa ).sum() _a = np.equal(__a , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(__a , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase , lowerCamelCase_ ): """simple docstring""" __a =True __a =( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) __a =(FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def UpperCamelCase__ ( self : List[Any] ): _a = FlaxBlenderbotModelTester(self ) def UpperCamelCase__ ( self : List[str] ): _a , _a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(__a , __a , __a ) def UpperCamelCase__ ( self : Optional[int] ): _a , _a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(__a , __a , __a ) def UpperCamelCase__ ( self : Any ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _a = self._prepare_for_class(__a , __a ) _a = model_class(__a ) @jax.jit def encode_jitted(__a : Tuple , __a : Union[str, Any]=None , **__a : Optional[Any] ): return model.encode(input_ids=__a , attention_mask=__a ) with self.subTest("JIT Enabled" ): _a = encode_jitted(**__a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): _a = encode_jitted(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) ) for jitted_output, output in zip(__a , __a ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCamelCase__ ( self : Optional[int] ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _a = model_class(__a ) _a = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) _a = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(__a : Dict , __a : str , __a : Tuple ): return model.decode( decoder_input_ids=__a , decoder_attention_mask=__a , encoder_outputs=__a , ) with self.subTest("JIT Enabled" ): _a = decode_jitted(**__a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): _a = decode_jitted(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) ) for jitted_output, output in zip(__a , __a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase__ ( self : Dict ): for model_class_name in self.all_model_classes: _a = model_class_name.from_pretrained("facebook/blenderbot-400M-distill" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids _a = np.ones((1, 1) ) * model.config.eos_token_id _a = model(__a ) self.assertIsNotNone(__a ) @unittest.skipUnless(jax_device != "cpu" , "3B test too slow on CPU." ) @slow def UpperCamelCase__ ( self : List[str] ): _a = {"num_beams": 1, "early_stopping": True, "min_length": 15, "max_length": 25} _a = {"skip_special_tokens": True, "clean_up_tokenization_spaces": True} _a = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-3B" , from_pt=__a ) _a = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-3B" ) _a = ["Sam"] _a = tokenizer(__a , return_tensors="jax" ) _a = model.generate(**__a , **__a ) _a = "Sam is a great name. It means \"sun\" in Gaelic." _a = tokenizer.batch_decode(__a , **__a ) assert generated_txt[0].strip() == tgt_text
63
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def UpperCAmelCase__ (snake_case__ : str , snake_case__ : float | Decimal , snake_case__ : float = 10**-10 ): """simple docstring""" _snake_case : Optional[Any] = a while True: _snake_case : Optional[Any] = Decimal(snake_case__ ) - ( Decimal(eval(snake_case__ ) ) / Decimal(eval(str(diff(snake_case__ ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(snake_case__ ) ) < precision: # noqa: S307 return float(snake_case__ ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F'''The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}''') # Find root of polynomial print(F'''The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}''') # Find Square Root of 5 print(F'''The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}''') # Exponential Roots print(F'''The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}''')
64
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
0
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(UpperCAmelCase_ ) , 'Tatoeba directory does not exist.' ) class A ( unittest.TestCase ): @cached_property def lowercase_ (self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = tempfile.mkdtemp() return TatoebaConverter(save_dir=__UpperCAmelCase ) @slow def lowercase_ (self : List[Any] ) -> Optional[int]: """simple docstring""" self.resolver.convert_models(["heb-eng"] ) @slow def lowercase_ (self : Dict ) -> List[str]: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.resolver.write_model_card("opus-mt-he-en" , dry_run=__UpperCAmelCase ) assert mmeta["long_pair"] == "heb-eng"
65
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __a = "\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n" __a = "\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper \"Evaluating Large Language Models Trained on Code\"\n(https://arxiv.org/abs/2107.03374).\n" __a = "\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric(\"code_eval\")\n >>> test_cases = [\"assert add(2,3)==5\"]\n >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {'pass@1': 0.5, 'pass@2': 1.0}\n" __a = "\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe \"code_eval\" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper \"Evaluating Large\nLanguage Models Trained on Code\" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"\n\n################################################################################\\n" __a = "The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE." @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase ( datasets.Metric ): '''simple docstring''' def lowerCAmelCase_ ( self: Union[str, Any] ) -> Optional[int]: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def lowerCAmelCase_ ( self: Union[str, Any] , snake_case: Union[str, Any] , snake_case: Tuple , snake_case: Optional[int]=[1, 10, 100] , snake_case: Dict=4 , snake_case: List[str]=3.0 ) -> List[Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""" ) with ThreadPoolExecutor(max_workers=snake_case ) as executor: snake_case_ :Union[str, Any] = [] snake_case_ :Optional[Any] = Counter() snake_case_ :List[Any] = 0 snake_case_ :Optional[Any] = defaultdict(snake_case ) for task_id, (candidates, test_case) in enumerate(zip(snake_case , snake_case ) ): for candidate in candidates: snake_case_ :Dict = candidate + """\n""" + test_case snake_case_ :List[Any] = (test_program, timeout, task_id, completion_id[task_id]) snake_case_ :List[Any] = executor.submit(snake_case , *snake_case ) futures.append(snake_case ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(snake_case ): snake_case_ :Any = future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) snake_case_, snake_case_ :Union[str, Any] = [], [] for result in results.values(): result.sort() snake_case_ :Dict = [r[1]["""passed"""] for r in result] total.append(len(snake_case ) ) correct.append(sum(snake_case ) ) snake_case_ :Union[str, Any] = np.array(snake_case ) snake_case_ :Any = np.array(snake_case ) snake_case_ :int = k snake_case_ :str = {f"""pass@{k}""": estimate_pass_at_k(snake_case , snake_case , snake_case ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' def estimator(_lowercase, _lowercase, _lowercase ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1 ) ) if isinstance(_lowercase, _lowercase ): snake_case_ :List[Any] = itertools.repeat(_lowercase, len(_lowercase ) ) else: assert len(_lowercase ) == len(_lowercase ) snake_case_ :Optional[int] = iter(_lowercase ) return np.array([estimator(int(_lowercase ), int(_lowercase ), _lowercase ) for n, c in zip(_lowercase, _lowercase )] )
66
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
0
'''simple docstring''' import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class a__ ( UpperCAmelCase__ ): lowerCamelCase : Tuple ="char" lowerCamelCase : List[str] ="bpe" lowerCamelCase : Tuple ="wp" __UpperCAmelCase =(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class a__ ( UpperCAmelCase__ ): lowerCamelCase : List[str] =["image_processor", "char_tokenizer"] lowerCamelCase : List[Any] ="ViTImageProcessor" lowerCamelCase : Tuple ="MgpstrTokenizer" def __init__( self : int , a : str=None , a : int=None , **a : List[Any] ): """simple docstring""" __lowerCamelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a , ) __lowerCamelCase = kwargs.pop('''feature_extractor''' ) __lowerCamelCase = 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`.''' ) __lowerCamelCase = tokenizer __lowerCamelCase = AutoTokenizer.from_pretrained('''gpt2''' ) __lowerCamelCase = AutoTokenizer.from_pretrained('''bert-base-uncased''' ) super().__init__(a , a ) def __call__( self : Optional[Any] , a : Tuple=None , a : Dict=None , a : List[Any]=None , **a : Optional[int] ): """simple docstring""" 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: __lowerCamelCase = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase = encodings['''input_ids'''] return inputs def SCREAMING_SNAKE_CASE__ ( self : Dict , a : Optional[Any] ): """simple docstring""" __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = sequences __lowerCamelCase = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase = self._decode_helper(a , '''char''' ) __lowerCamelCase , __lowerCamelCase = self._decode_helper(a , '''bpe''' ) __lowerCamelCase , __lowerCamelCase = self._decode_helper(a , '''wp''' ) __lowerCamelCase = [] __lowerCamelCase = [] for i in range(a ): __lowerCamelCase = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase = {} __lowerCamelCase = final_strs __lowerCamelCase = final_scores __lowerCamelCase = char_strs __lowerCamelCase = bpe_strs __lowerCamelCase = wp_strs return out def SCREAMING_SNAKE_CASE__ ( self : Dict , a : Tuple , a : List[str] ): """simple docstring""" if format == DecodeType.CHARACTER: __lowerCamelCase = self.char_decode __lowerCamelCase = 1 __lowerCamelCase = '''[s]''' elif format == DecodeType.BPE: __lowerCamelCase = self.bpe_decode __lowerCamelCase = 2 __lowerCamelCase = '''#''' elif format == DecodeType.WORDPIECE: __lowerCamelCase = self.wp_decode __lowerCamelCase = 1_02 __lowerCamelCase = '''[SEP]''' else: raise ValueError(f"""Format {format} is not supported.""" ) __lowerCamelCase , __lowerCamelCase = [], [] __lowerCamelCase = pred_logits.size(0 ) __lowerCamelCase = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase = decoder(a ) __lowerCamelCase , __lowerCamelCase = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase = preds_str[index].find(a ) __lowerCamelCase = preds_str[index][:pred_eos] __lowerCamelCase = preds_index[index].cpu().tolist() __lowerCamelCase = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(a ) conf_scores.append(a ) return dec_strs, conf_scores def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : Tuple ): """simple docstring""" __lowerCamelCase = [seq.replace(''' ''' , '''''' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : Union[str, Any] ): """simple docstring""" return self.bpe_tokenizer.batch_decode(a ) def SCREAMING_SNAKE_CASE__ ( self : Dict , a : Tuple ): """simple docstring""" __lowerCamelCase = [seq.replace(''' ''' , '''''' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
67
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
0
from __future__ import annotations lowerCAmelCase__ = 1.6_021e-19 # units = C def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: float , SCREAMING_SNAKE_CASE_: float , SCREAMING_SNAKE_CASE_: float , ) -> tuple[str, float]: '''simple docstring''' if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif conductivity < 0: raise ValueError("Conductivity cannot be negative" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative" ) elif mobility < 0: raise ValueError("mobility cannot be negative" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
68
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = None class UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = 2 @register_to_config def __init__( self, lowerCAmelCase__ = 0.02, lowerCAmelCase__ = 100, lowerCAmelCase__ = 1.007, lowerCAmelCase__ = 80, lowerCAmelCase__ = 0.05, lowerCAmelCase__ = 50, ) -> List[str]: # standard deviation of the initial noise distribution snake_case_ = sigma_max # setable values snake_case_ = None snake_case_ = None snake_case_ = None # sigma(t_i) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None) -> torch.FloatTensor: return sample def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None) -> int: snake_case_ = num_inference_steps snake_case_ = np.arange(0, self.num_inference_steps)[::-1].copy() snake_case_ = torch.from_numpy(lowerCAmelCase__).to(lowerCAmelCase__) snake_case_ = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] snake_case_ = torch.tensor(lowerCAmelCase__, dtype=torch.floataa, device=lowerCAmelCase__) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = None) -> Tuple[torch.FloatTensor, float]: if self.config.s_min <= sigma <= self.config.s_max: snake_case_ = min(self.config.s_churn / self.num_inference_steps, 2**0.5 - 1) else: snake_case_ = 0 # sample eps ~ N(0, S_noise^2 * I) snake_case_ = self.config.s_noise * randn_tensor(sample.shape, generator=lowerCAmelCase__).to(sample.device) snake_case_ = sigma + gamma * sigma snake_case_ = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = True, ) -> Union[KarrasVeOutput, Tuple]: snake_case_ = sample_hat + sigma_hat * model_output snake_case_ = (sample_hat - pred_original_sample) / sigma_hat snake_case_ = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=lowerCAmelCase__, derivative=lowerCAmelCase__, pred_original_sample=lowerCAmelCase__) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = True, ) -> Union[KarrasVeOutput, Tuple]: snake_case_ = sample_prev + sigma_prev * model_output snake_case_ = (sample_prev - pred_original_sample) / sigma_prev snake_case_ = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=lowerCAmelCase__, derivative=lowerCAmelCase__, pred_original_sample=lowerCAmelCase__) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__) -> List[str]: raise NotImplementedError()
69
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL A__ : List[str] =logging.get_logger(__name__) def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" if isinstance(lowerCAmelCase , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowerCAmelCase , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowerCAmelCase ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class UpperCAmelCase ( snake_case_ ): _lowercase: Any = ['''pixel_values'''] def __init__( self : Tuple , __snake_case : bool = True , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : bool = True , __snake_case : Dict[str, int] = None , __snake_case : bool = True , __snake_case : Union[int, float] = 1 / 2_55 , __snake_case : bool = True , __snake_case : bool = True , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[float, List[float]]] = None , **__snake_case : str , ) -> None: super().__init__(**__snake_case ) _lowerCAmelCase = size if size is not None else {"""shortest_edge""": 2_56} _lowerCAmelCase = get_size_dict(__snake_case , default_to_square=__snake_case ) _lowerCAmelCase = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24} _lowerCAmelCase = get_size_dict(__snake_case , param_name="""crop_size""" ) _lowerCAmelCase = do_resize _lowerCAmelCase = size _lowerCAmelCase = do_center_crop _lowerCAmelCase = crop_size _lowerCAmelCase = resample _lowerCAmelCase = do_rescale _lowerCAmelCase = rescale_factor _lowerCAmelCase = offset _lowerCAmelCase = do_normalize _lowerCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowerCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowercase__ ( self : int , __snake_case : np.ndarray , __snake_case : Dict[str, int] , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : Optional[Any] , ) -> np.ndarray: _lowerCAmelCase = get_size_dict(__snake_case , default_to_square=__snake_case ) if "shortest_edge" in size: _lowerCAmelCase = get_resize_output_image_size(__snake_case , size["""shortest_edge"""] , default_to_square=__snake_case ) elif "height" in size and "width" in size: _lowerCAmelCase = (size["""height"""], size["""width"""]) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(__snake_case , size=__snake_case , resample=__snake_case , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : Union[str, Any] , __snake_case : np.ndarray , __snake_case : Dict[str, int] , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : List[Any] , ) -> np.ndarray: _lowerCAmelCase = get_size_dict(__snake_case ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(__snake_case , size=(size["""height"""], size["""width"""]) , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : Union[str, Any] , __snake_case : np.ndarray , __snake_case : Union[int, float] , __snake_case : bool = True , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : Optional[Any] , ) -> Dict: _lowerCAmelCase = image.astype(np.floataa ) if offset: _lowerCAmelCase = image - (scale / 2) return rescale(__snake_case , scale=__snake_case , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : Optional[int] , __snake_case : np.ndarray , __snake_case : Union[float, List[float]] , __snake_case : Union[float, List[float]] , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : Tuple , ) -> np.ndarray: return normalize(__snake_case , mean=__snake_case , std=__snake_case , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : List[Any] , __snake_case : ImageInput , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = None , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : bool = None , __snake_case : float = None , __snake_case : bool = None , __snake_case : bool = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.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_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) if offset and not do_rescale: raise ValueError("""For offset, do_rescale must also be set to True.""" ) # All transformations expect numpy arrays. _lowerCAmelCase = to_numpy_array(__snake_case ) if do_resize: _lowerCAmelCase = self.resize(image=__snake_case , size=__snake_case , resample=__snake_case ) if do_center_crop: _lowerCAmelCase = self.center_crop(__snake_case , size=__snake_case ) if do_rescale: _lowerCAmelCase = self.rescale(image=__snake_case , scale=__snake_case , offset=__snake_case ) if do_normalize: _lowerCAmelCase = self.normalize(image=__snake_case , mean=__snake_case , std=__snake_case ) _lowerCAmelCase = to_channel_dimension_format(__snake_case , __snake_case ) return image def lowercase__ ( self : List[Any] , __snake_case : ImageInput , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = None , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : bool = None , __snake_case : float = None , __snake_case : bool = None , __snake_case : bool = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[str, TensorType]] = None , __snake_case : ChannelDimension = ChannelDimension.FIRST , **__snake_case : List[str] , ) -> PIL.Image.Image: _lowerCAmelCase = do_resize if do_resize is not None else self.do_resize _lowerCAmelCase = resample if resample is not None else self.resample _lowerCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop _lowerCAmelCase = do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase = offset if offset is not None else self.offset _lowerCAmelCase = do_normalize if do_normalize is not None else self.do_normalize _lowerCAmelCase = image_mean if image_mean is not None else self.image_mean _lowerCAmelCase = image_std if image_std is not None else self.image_std _lowerCAmelCase = size if size is not None else self.size _lowerCAmelCase = get_size_dict(__snake_case , default_to_square=__snake_case ) _lowerCAmelCase = crop_size if crop_size is not None else self.crop_size _lowerCAmelCase = get_size_dict(__snake_case , param_name="""crop_size""" ) if not valid_images(__snake_case ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) _lowerCAmelCase = make_batched(__snake_case ) _lowerCAmelCase = [ [ self._preprocess_image( image=__snake_case , do_resize=__snake_case , size=__snake_case , resample=__snake_case , do_center_crop=__snake_case , crop_size=__snake_case , do_rescale=__snake_case , rescale_factor=__snake_case , offset=__snake_case , do_normalize=__snake_case , image_mean=__snake_case , image_std=__snake_case , data_format=__snake_case , ) for img in video ] for video in videos ] _lowerCAmelCase = {"""pixel_values""": videos} return BatchFeature(data=__snake_case , tensor_type=__snake_case )
70
"""simple docstring""" import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
0
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ :Any = logging.get_logger(__name__) A_ :int = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __A ( a ): """simple docstring""" UpperCamelCase__ : Optional[int] ="""vit_msn""" def __init__( self , lowerCamelCase__=768 , lowerCamelCase__=12 , lowerCamelCase__=12 , lowerCamelCase__=3072 , lowerCamelCase__="gelu" , lowerCamelCase__=0.0 , lowerCamelCase__=0.0 , lowerCamelCase__=0.02 , lowerCamelCase__=1E-06 , lowerCamelCase__=224 , lowerCamelCase__=16 , lowerCamelCase__=3 , lowerCamelCase__=True , **lowerCamelCase__ , ): """simple docstring""" super().__init__(**lowerCamelCase__ ) __UpperCamelCase : int =hidden_size __UpperCamelCase : List[Any] =num_hidden_layers __UpperCamelCase : Union[str, Any] =num_attention_heads __UpperCamelCase : List[str] =intermediate_size __UpperCamelCase : Union[str, Any] =hidden_act __UpperCamelCase : str =hidden_dropout_prob __UpperCamelCase : Union[str, Any] =attention_probs_dropout_prob __UpperCamelCase : Union[str, Any] =initializer_range __UpperCamelCase : Tuple =layer_norm_eps __UpperCamelCase : Optional[Any] =image_size __UpperCamelCase : Optional[int] =patch_size __UpperCamelCase : Any =num_channels __UpperCamelCase : str =qkv_bias
71
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
"""simple docstring""" def snake_case_ ( A_ : Tuple, A_ : Tuple, A_ : Any, A_ : Optional[Any] ): '''simple docstring''' _lowerCamelCase : int = [False] * len(A_ ) _lowerCamelCase : Union[str, Any] = [] queue.append(A_ ) _lowerCamelCase : str = True while queue: _lowerCamelCase : List[Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(A_ ) _lowerCamelCase : int = True _lowerCamelCase : Union[str, Any] = u return visited[t] def snake_case_ ( A_ : Union[str, Any], A_ : str, A_ : int ): '''simple docstring''' _lowerCamelCase : Optional[Any] = [-1] * (len(A_ )) _lowerCamelCase : Optional[Any] = 0 while bfs(A_, A_, A_, A_ ): _lowerCamelCase : Optional[Any] = float('''Inf''' ) _lowerCamelCase : Union[str, Any] = sink while s != source: # Find the minimum value in select path _lowerCamelCase : Union[str, Any] = min(A_, graph[parent[s]][s] ) _lowerCamelCase : List[str] = parent[s] max_flow += path_flow _lowerCamelCase : List[str] = sink while v != source: _lowerCamelCase : Union[str, Any] = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _lowerCamelCase : Optional[Any] = parent[v] return max_flow lowerCAmelCase__ = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] lowerCAmelCase__ , lowerCAmelCase__ = 0, 5 print(ford_fulkerson(graph, source, sink))
72
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
0
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('dataset_size' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('input_in_memory_max_size' , ['default', 0, 100 * 2**20, 900 * 2**20] ) def _snake_case ( snake_case__ : List[Any] , snake_case__ : List[Any] , snake_case__ : int ): if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , 'IN_MEMORY_MAX_SIZE' , snake_case__ ) A = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: A = dataset_size < in_memory_max_size else: A = False A = is_small_dataset(snake_case__ ) assert result == expected
74
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
0
'''simple docstring''' from __future__ import annotations def a_ ( __snake_case : float , __snake_case : float , __snake_case : float ) -> dict[str, float]: """simple docstring""" if (voltage, current, resistance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance < 0: raise ValueError('''Resistance cannot be negative''' ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
75
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
0
from __future__ import annotations def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = position SCREAMING_SNAKE_CASE : Optional[int] = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] SCREAMING_SNAKE_CASE : Optional[int] = [] for position in positions: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(_a) return permissible_positions def lowerCamelCase__ ( _a): return not any(elem == 0 for row in board for elem in row) def lowerCamelCase__ ( _a , _a , _a): if is_complete(_a): return True for position in get_valid_pos(_a , len(_a)): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[Any] = position if board[y][x] == 0: SCREAMING_SNAKE_CASE : Any = curr + 1 if open_knight_tour_helper(_a , _a , curr + 1): return True SCREAMING_SNAKE_CASE : int = 0 return False def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : List[str] = [[0 for i in range(_a)] for j in range(_a)] for i in range(_a): for j in range(_a): SCREAMING_SNAKE_CASE : List[Any] = 1 if open_knight_tour_helper(_a , (i, j) , 1): return board SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Dict = f"Open Kight Tour cannot be performed on a board of size {n}" raise ValueError(_a) if __name__ == "__main__": import doctest doctest.testmod()
76
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
0
"""simple docstring""" def a_ ( _lowerCAmelCase : str ): '''simple docstring''' lowercase__ : Dict = [int(_lowerCAmelCase ) for i in ip_va_address.split('.' ) if i.isdigit()] return len(_lowerCAmelCase ) == 4 and all(0 <= int(_lowerCAmelCase ) <= 254 for octet in octets ) if __name__ == "__main__": _UpperCamelCase : Optional[Any] = input().strip() _UpperCamelCase : Union[str, Any] = "valid" if is_ip_va_address_valid(ip) else "invalid" print(f'''{ip} is a {valid_or_invalid} IP v4 address.''')
77
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available snake_case_ = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
78
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''andreasmadsen/efficient_mlm_m0.40''': ( '''https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json''' ), } class _UpperCAmelCase ( snake_case_ ): """simple docstring""" snake_case = '''roberta-prelayernorm''' def __init__( self : Union[str, Any] , __UpperCAmelCase : List[str]=50265 , __UpperCAmelCase : int=768 , __UpperCAmelCase : List[Any]=12 , __UpperCAmelCase : Tuple=12 , __UpperCAmelCase : str=3072 , __UpperCAmelCase : Union[str, Any]="gelu" , __UpperCAmelCase : str=0.1 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : Optional[int]=512 , __UpperCAmelCase : List[Any]=2 , __UpperCAmelCase : str=0.02 , __UpperCAmelCase : List[Any]=1E-12 , __UpperCAmelCase : Optional[int]=1 , __UpperCAmelCase : str=0 , __UpperCAmelCase : Tuple=2 , __UpperCAmelCase : List[str]="absolute" , __UpperCAmelCase : Any=True , __UpperCAmelCase : Union[str, Any]=None , **__UpperCAmelCase : Optional[int] , ): '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) _A = vocab_size _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = hidden_act _A = intermediate_size _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = max_position_embeddings _A = type_vocab_size _A = initializer_range _A = layer_norm_eps _A = position_embedding_type _A = use_cache _A = classifier_dropout class _UpperCAmelCase ( snake_case_ ): """simple docstring""" @property def lowerCAmelCase ( self : str ): '''simple docstring''' if self.task == "multiple-choice": _A = {0: "batch", 1: "choice", 2: "sequence"} else: _A = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
79
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = pipeline( 'document-question-answering' , model='naver-clova-ix/donut-base-finetuned-docvqa' , tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa' ) , feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
0
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> np.ndarray: '''simple docstring''' UpperCamelCase__ = cva.getAffineTransform(__A , __A ) return cva.warpAffine(__A , __A , (rows, cols) ) if __name__ == "__main__": # read original image a__ : Dict = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value a__ : Optional[int] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a__ , a__ : Union[str, Any] = gray_img.shape # set different points to rotate image a__ : int = np.array([[5_0, 5_0], [2_0_0, 5_0], [5_0, 2_0_0]], np.floataa) a__ : Tuple = np.array([[1_0, 1_0_0], [2_0_0, 5_0], [1_0_0, 2_5_0]], np.floataa) a__ : Union[str, Any] = np.array([[5_0, 5_0], [1_5_0, 5_0], [1_2_0, 2_0_0]], np.floataa) a__ : Optional[Any] = np.array([[1_0, 1_0_0], [8_0, 5_0], [1_8_0, 2_5_0]], np.floataa) # add all rotated images in a list a__ : List[Any] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a__ : str = plt.figure(1) a__ : str = ['Original', 'Rotation 1', 'Rotation 2', 'Rotation 3'] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, 'gray') plt.title(titles[i]) plt.axis('off') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
80
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
0
"""simple docstring""" def _A ( lowercase ): """simple docstring""" if n_term == "": return [] a =[] for temp in range(int(lowercase ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowerCamelCase_ : Union[str, Any] = input("""Enter the last number (nth term) of the Harmonic Series""") print("""Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n""") print(harmonic_series(nth_term))
81
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
0
from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar A__ = TypeVar("""T""") A__ = TypeVar("""U""") class __lowerCAmelCase ( Generic[T, U] ): def __init__( self , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = key _lowerCAmelCase = val _lowerCAmelCase = None _lowerCAmelCase = None def __repr__( self ): """simple docstring""" return ( F'Node: key: {self.key}, val: {self.val}, ' F'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class __lowerCAmelCase ( Generic[T, U] ): def __init__( self ): """simple docstring""" _lowerCAmelCase = DoubleLinkedListNode(_snake_case , _snake_case ) _lowerCAmelCase = DoubleLinkedListNode(_snake_case , _snake_case ) _lowerCAmelCase , _lowerCAmelCase = self.rear, self.head def __repr__( self ): """simple docstring""" _lowerCAmelCase = ["""DoubleLinkedList"""] _lowerCAmelCase = self.head while node.next is not None: rep.append(str(_snake_case ) ) _lowerCAmelCase = node.next rep.append(str(self.rear ) ) return ",\n ".join(_snake_case ) def snake_case ( self , _snake_case ): """simple docstring""" _lowerCAmelCase = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None _lowerCAmelCase = node _lowerCAmelCase = previous _lowerCAmelCase = node _lowerCAmelCase = self.rear def snake_case ( self , _snake_case ): """simple docstring""" if node.prev is None or node.next is None: return None _lowerCAmelCase = node.next _lowerCAmelCase = node.prev _lowerCAmelCase = None _lowerCAmelCase = None return node class __lowerCAmelCase ( Generic[T, U] ): __lowerCamelCase = {} def __init__( self , _snake_case ): """simple docstring""" _lowerCAmelCase = DoubleLinkedList() _lowerCAmelCase = capacity _lowerCAmelCase = 0 _lowerCAmelCase = 0 _lowerCAmelCase = 0 _lowerCAmelCase = {} def __repr__( self ): """simple docstring""" return ( F'CacheInfo(hits={self.hits}, misses={self.miss}, ' F'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self , _snake_case ): """simple docstring""" return key in self.cache def snake_case ( self , _snake_case ): """simple docstring""" if key in self.cache: self.hits += 1 _lowerCAmelCase = self.cache[key] _lowerCAmelCase = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(_snake_case ) return node.val self.miss += 1 return None def snake_case ( self , _snake_case , _snake_case ): """simple docstring""" if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity _lowerCAmelCase = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(_snake_case ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 _lowerCAmelCase = DoubleLinkedListNode(_snake_case , _snake_case ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value _lowerCAmelCase = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list _lowerCAmelCase = value self.list.add(_snake_case ) @classmethod def snake_case ( cls , _snake_case = 128 ): """simple docstring""" def cache_decorator_inner(_snake_case ) -> Callable[..., U]: def cache_decorator_wrapper(*_snake_case ) -> U: if func not in cls.decorator_function_to_instance_map: _lowerCAmelCase = LRUCache(_snake_case ) _lowerCAmelCase = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: _lowerCAmelCase = func(*_snake_case ) cls.decorator_function_to_instance_map[func].put(args[0] , _snake_case ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(_snake_case , """cache_info""" , _snake_case ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
82
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
0
'''simple docstring''' from typing import List import numpy as np def A__ ( UpperCAmelCase_ ): _UpperCamelCase : Optional[Any] = {key: len(UpperCAmelCase_ ) for key, value in gen_kwargs.items() if isinstance(UpperCAmelCase_ , UpperCAmelCase_ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( 'Sharding is ambiguous for this dataset: ' + 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n' + '\n'.join(f'\t- key {key} has length {length}' for key, length in lists_lengths.items() ) + '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ' + 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.' ) ) _UpperCamelCase : Union[str, Any] = max(lists_lengths.values() , default=0 ) return max(1 , UpperCAmelCase_ ) def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Dict = [] for group_idx in range(UpperCAmelCase_ ): _UpperCamelCase : Tuple = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break _UpperCamelCase : Union[str, Any] = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 _UpperCamelCase : Union[str, Any] = range(UpperCAmelCase_ , start + num_shards_to_add ) shards_indices_per_group.append(UpperCAmelCase_ ) return shards_indices_per_group def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : List[str] = _number_of_shards_in_gen_kwargs(UpperCAmelCase_ ) if num_shards == 1: return [dict(UpperCAmelCase_ )] else: _UpperCamelCase : str = _distribute_shards(num_shards=UpperCAmelCase_ , max_num_jobs=UpperCAmelCase_ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(UpperCAmelCase_ ) ) ] def A__ ( UpperCAmelCase_ ): return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , UpperCAmelCase_ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Optional[Any] = {len(UpperCAmelCase_ ) for value in gen_kwargs.values() if isinstance(UpperCAmelCase_ , UpperCAmelCase_ )} _UpperCamelCase : Tuple = {} for size in list_sizes: _UpperCamelCase : str = list(range(UpperCAmelCase_ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes _UpperCamelCase : Tuple = dict(UpperCAmelCase_ ) for key, value in shuffled_kwargs.items(): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Tuple = [value[i] for i in indices_per_size[len(UpperCAmelCase_ )]] return shuffled_kwargs
83
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _SCREAMING_SNAKE_CASE ( A__ , unittest.TestCase ): # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @property def __lowerCAmelCase ( self ) -> List[Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __lowerCAmelCase ( self ) -> Any: lowerCAmelCase_ :str = ort.SessionOptions() lowerCAmelCase_ :int = False return options def __lowerCAmelCase ( self ) -> List[str]: lowerCAmelCase_ :Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) lowerCAmelCase_ :List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) lowerCAmelCase_ :List[Any] = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , safety_checker=__A , feature_extractor=__A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__A ) lowerCAmelCase_ :Dict = """A red cat sitting on a park bench""" lowerCAmelCase_ :int = np.random.RandomState(0 ) lowerCAmelCase_ :Dict = pipe( prompt=__A , image=__A , mask_image=__A , guidance_scale=7.5 , num_inference_steps=10 , generator=__A , output_type="""np""" , ) lowerCAmelCase_ :Dict = output.images lowerCAmelCase_ :Tuple = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) lowerCAmelCase_ :str = np.array([0.2_5_1_4, 0.3_0_0_7, 0.3_5_1_7, 0.1_7_9_0, 0.2_3_8_2, 0.3_1_6_7, 0.1_9_4_4, 0.2_2_7_3, 0.2_4_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def __lowerCAmelCase ( self ) -> List[str]: lowerCAmelCase_ :int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) lowerCAmelCase_ :int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) lowerCAmelCase_ :List[str] = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-inpainting""" , subfolder="""scheduler""" , revision="""onnx""" ) lowerCAmelCase_ :str = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , scheduler=__A , safety_checker=__A , feature_extractor=__A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__A ) lowerCAmelCase_ :Optional[Any] = """A red cat sitting on a park bench""" lowerCAmelCase_ :str = np.random.RandomState(0 ) lowerCAmelCase_ :Dict = pipe( prompt=__A , image=__A , mask_image=__A , guidance_scale=7.5 , num_inference_steps=20 , generator=__A , output_type="""np""" , ) lowerCAmelCase_ :Any = output.images lowerCAmelCase_ :Any = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) lowerCAmelCase_ :Optional[int] = np.array([0.0_0_8_6, 0.0_0_7_7, 0.0_0_8_3, 0.0_0_9_3, 0.0_1_0_7, 0.0_1_3_9, 0.0_0_9_4, 0.0_0_9_7, 0.0_1_2_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
84
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[Any] = { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json", "junnyu/roformer_chinese_base": "https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json", "junnyu/roformer_chinese_char_small": ( "https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json" ), "junnyu/roformer_chinese_char_base": ( "https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json" ), "junnyu/roformer_small_discriminator": ( "https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json" ), "junnyu/roformer_small_generator": ( "https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Dict = "roformer" def __init__( self , a__=50_000 , a__=None , a__=768 , a__=12 , a__=12 , a__=3_072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=1_536 , a__=2 , a__=0.0_2 , a__=1e-12 , a__=0 , a__=False , a__=True , **a__ , ) -> Tuple: '''simple docstring''' super().__init__(pad_token_id=a__ , **a__ ) snake_case_ = vocab_size snake_case_ = hidden_size if embedding_size is None else embedding_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = rotary_value snake_case_ = use_cache class _snake_case ( lowercase_ ): @property def lowerCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": snake_case_ = {0: "batch", 1: "choice", 2: "sequence"} else: snake_case_ = {0: "batch", 1: "sequence"} snake_case_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
85
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class A__ ( _lowerCamelCase): A_ : Dict = (DDPMParallelScheduler,) def __lowerCamelCase ( self , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = { 'num_train_timesteps': 10_00, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'variance_type': 'fixed_small', 'clip_sample': True, } config.update(**_SCREAMING_SNAKE_CASE ) return config def __lowerCamelCase ( self ): for timesteps in [1, 5, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_SCREAMING_SNAKE_CASE , beta_end=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): self.check_over_configs(thresholding=_SCREAMING_SNAKE_CASE ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_SCREAMING_SNAKE_CASE , prediction_type=_SCREAMING_SNAKE_CASE , sample_max_value=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self ): for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for t in [0, 5_00, 9_99]: self.check_over_forward(time_step=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.scheduler_classes[0] __lowerCAmelCase : Dict = self.get_scheduler_config() __lowerCAmelCase : Any = scheduler_class(**_SCREAMING_SNAKE_CASE ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 ) - 0.0_0979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 ) - 0.02 ) ) < 1E-5 def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.scheduler_classes[0] __lowerCAmelCase : str = self.get_scheduler_config() __lowerCAmelCase : Any = scheduler_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.dummy_model() __lowerCAmelCase : List[Any] = self.dummy_sample_deter __lowerCAmelCase : int = self.dummy_sample_deter + 0.1 __lowerCAmelCase : Tuple = self.dummy_sample_deter - 0.1 __lowerCAmelCase : Tuple = samplea.shape[0] __lowerCAmelCase : Tuple = torch.stack([samplea, samplea, samplea] , dim=0 ) __lowerCAmelCase : str = torch.arange(_SCREAMING_SNAKE_CASE )[0:3, None].repeat(1 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __lowerCAmelCase : Tuple = scheduler.batch_step_no_noise(_SCREAMING_SNAKE_CASE , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) __lowerCAmelCase : Optional[Any] = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : int = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 1153.1833 ) < 1E-2 assert abs(result_mean.item() - 0.5005 ) < 1E-3 def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.scheduler_classes[0] __lowerCAmelCase : Any = self.get_scheduler_config() __lowerCAmelCase : Optional[Any] = scheduler_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = len(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = self.dummy_model() __lowerCAmelCase : List[str] = self.dummy_sample_deter __lowerCAmelCase : str = torch.manual_seed(0 ) for t in reversed(range(_SCREAMING_SNAKE_CASE ) ): # 1. predict noise residual __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # 2. predict previous mean of sample x_t-1 __lowerCAmelCase : Tuple = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE ).prev_sample __lowerCAmelCase : Any = pred_prev_sample __lowerCAmelCase : Union[str, Any] = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : List[str] = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 258.9606 ) < 1E-2 assert abs(result_mean.item() - 0.3372 ) < 1E-3 def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = self.scheduler_classes[0] __lowerCAmelCase : str = self.get_scheduler_config(prediction_type='v_prediction' ) __lowerCAmelCase : Tuple = scheduler_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = len(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = self.dummy_model() __lowerCAmelCase : Any = self.dummy_sample_deter __lowerCAmelCase : int = torch.manual_seed(0 ) for t in reversed(range(_SCREAMING_SNAKE_CASE ) ): # 1. predict noise residual __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # 2. predict previous mean of sample x_t-1 __lowerCAmelCase : List[Any] = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE ).prev_sample __lowerCAmelCase : int = pred_prev_sample __lowerCAmelCase : int = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Optional[Any] = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 202.0296 ) < 1E-2 assert abs(result_mean.item() - 0.2631 ) < 1E-3 def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.scheduler_classes[0] __lowerCAmelCase : Optional[Any] = self.get_scheduler_config() __lowerCAmelCase : Tuple = scheduler_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = [1_00, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = scheduler.timesteps for i, timestep in enumerate(_SCREAMING_SNAKE_CASE ): if i == len(_SCREAMING_SNAKE_CASE ) - 1: __lowerCAmelCase : Optional[int] = -1 else: __lowerCAmelCase : Dict = timesteps[i + 1] __lowerCAmelCase : Optional[int] = scheduler.previous_timestep(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = prev_t.item() self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.scheduler_classes[0] __lowerCAmelCase : List[Any] = self.get_scheduler_config() __lowerCAmelCase : Union[str, Any] = scheduler_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = [1_00, 87, 50, 51, 0] with self.assertRaises(_SCREAMING_SNAKE_CASE , msg='`custom_timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.scheduler_classes[0] __lowerCAmelCase : List[str] = self.get_scheduler_config() __lowerCAmelCase : Optional[Any] = scheduler_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [1_00, 87, 50, 1, 0] __lowerCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) with self.assertRaises(_SCREAMING_SNAKE_CASE , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ): scheduler.set_timesteps(num_inference_steps=_SCREAMING_SNAKE_CASE , timesteps=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.scheduler_classes[0] __lowerCAmelCase : Any = self.get_scheduler_config() __lowerCAmelCase : Optional[int] = scheduler_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = [scheduler.config.num_train_timesteps] with self.assertRaises( _SCREAMING_SNAKE_CASE , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=_SCREAMING_SNAKE_CASE )
86
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
0
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class snake_case_ : @staticmethod def __UpperCamelCase ( *lowercase_ : Optional[int] , **lowercase_ : Optional[int] ) -> List[Any]: pass @is_pipeline_test @require_vision @require_timm @require_torch class snake_case_ ( unittest.TestCase ): __A : str = MODEL_FOR_OBJECT_DETECTION_MAPPING def __UpperCamelCase ( self : Optional[Any] , lowercase_ : int , lowercase_ : List[str] , lowercase_ : Dict ) -> Any: lowercase__ : Union[str, Any] = ObjectDetectionPipeline(model=lowercase_ , image_processor=lowercase_ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def __UpperCamelCase ( self : Any , lowercase_ : Optional[int] , lowercase_ : List[str] ) -> Union[str, Any]: lowercase__ : Tuple = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0 ) self.assertGreater(len(lowercase_ ) , 0 ) for detected_object in outputs: self.assertEqual( lowercase_ , { "score": ANY(lowercase_ ), "label": ANY(lowercase_ ), "box": {"xmin": ANY(lowercase_ ), "ymin": ANY(lowercase_ ), "xmax": ANY(lowercase_ ), "ymax": ANY(lowercase_ )}, } , ) import datasets lowercase__ : List[Any] = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" ) lowercase__ : Union[str, Any] = [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ), "http://images.cocodataset.org/val2017/000000039769.jpg", # RGBA dataset[0]["file"], # LA dataset[1]["file"], # L dataset[2]["file"], ] lowercase__ : Optional[Any] = object_detector(lowercase_ , threshold=0.0 ) self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for outputs in batch_outputs: self.assertGreater(len(lowercase_ ) , 0 ) for detected_object in outputs: self.assertEqual( lowercase_ , { "score": ANY(lowercase_ ), "label": ANY(lowercase_ ), "box": {"xmin": ANY(lowercase_ ), "ymin": ANY(lowercase_ ), "xmax": ANY(lowercase_ ), "ymax": ANY(lowercase_ )}, } , ) @require_tf @unittest.skip("Object detection not implemented in TF" ) def __UpperCamelCase ( self : Dict ) -> int: pass @require_torch def __UpperCamelCase ( self : Optional[Any] ) -> Union[str, Any]: lowercase__ : Optional[int] = "hf-internal-testing/tiny-detr-mobilenetsv3" lowercase__ : Optional[Any] = AutoModelForObjectDetection.from_pretrained(lowercase_ ) lowercase__ : Tuple = AutoFeatureExtractor.from_pretrained(lowercase_ ) lowercase__ : Any = ObjectDetectionPipeline(model=lowercase_ , feature_extractor=lowercase_ ) lowercase__ : Any = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0 ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, ] , ) lowercase__ : Tuple = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ [ {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, ], [ {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, ], ] , ) @require_torch @slow def __UpperCamelCase ( self : List[str] ) -> int: lowercase__ : List[str] = "facebook/detr-resnet-50" lowercase__ : str = AutoModelForObjectDetection.from_pretrained(lowercase_ ) lowercase__ : int = AutoFeatureExtractor.from_pretrained(lowercase_ ) lowercase__ : Any = ObjectDetectionPipeline(model=lowercase_ , feature_extractor=lowercase_ ) lowercase__ : Optional[int] = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ] , ) lowercase__ : List[str] = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], ] , ) @require_torch @slow def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: lowercase__ : Optional[Any] = "facebook/detr-resnet-50" lowercase__ : Tuple = pipeline("object-detection" , model=lowercase_ ) lowercase__ : List[Any] = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ] , ) lowercase__ : Tuple = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], ] , ) @require_torch @slow def __UpperCamelCase ( self : str ) -> List[Any]: lowercase__ : int = 0.99_85 lowercase__ : Any = "facebook/detr-resnet-50" lowercase__ : List[str] = pipeline("object-detection" , model=lowercase_ ) lowercase__ : int = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=lowercase_ ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ] , ) @require_torch @require_pytesseract @slow def __UpperCamelCase ( self : List[str] ) -> List[str]: lowercase__ : Any = "Narsil/layoutlmv3-finetuned-funsd" lowercase__ : List[str] = 0.99_93 lowercase__ : Optional[Any] = pipeline("object-detection" , model=lowercase_ , threshold=lowercase_ ) lowercase__ : Dict = object_detector( "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png" ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [ {"score": 0.99_93, "label": "I-ANSWER", "box": {"xmin": 2_94, "ymin": 2_54, "xmax": 3_43, "ymax": 2_64}}, {"score": 0.99_93, "label": "I-ANSWER", "box": {"xmin": 2_94, "ymin": 2_54, "xmax": 3_43, "ymax": 2_64}}, ] , )
87
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __lowerCAmelCase : Tuple = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' __lowerCAmelCase : str = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' __lowerCAmelCase : Optional[int] = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' __lowerCAmelCase : Dict = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' __lowerCAmelCase : Union[str, Any] = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _lowercase ( self : Any ) -> str: """simple docstring""" return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def _lowercase ( self : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any]=[1, 10, 100] , UpperCamelCase__ : Tuple=4 , UpperCamelCase__ : Optional[Any]=3.0 ) -> List[str]: """simple docstring""" if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""" ) with ThreadPoolExecutor(max_workers=UpperCamelCase__ ) as executor: __magic_name__ = [] __magic_name__ = Counter() __magic_name__ = 0 __magic_name__ = defaultdict(UpperCamelCase__ ) for task_id, (candidates, test_case) in enumerate(zip(UpperCamelCase__ , UpperCamelCase__ ) ): for candidate in candidates: __magic_name__ = candidate + """\n""" + test_case __magic_name__ = (test_program, timeout, task_id, completion_id[task_id]) __magic_name__ = executor.submit(UpperCamelCase__ , *UpperCamelCase__ ) futures.append(UpperCamelCase__ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(UpperCamelCase__ ): __magic_name__ = future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) __magic_name__ , __magic_name__ = [], [] for result in results.values(): result.sort() __magic_name__ = [r[1]["""passed"""] for r in result] total.append(len(UpperCamelCase__ ) ) correct.append(sum(UpperCamelCase__ ) ) __magic_name__ = np.array(UpperCamelCase__ ) __magic_name__ = np.array(UpperCamelCase__ ) __magic_name__ = k __magic_name__ = {F'''pass@{k}''': estimate_pass_at_k(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def a__ ( A_, A_, A_ ): '''simple docstring''' def estimator(A_, A_, A_ ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1 ) ) if isinstance(A_, A_ ): __magic_name__ = itertools.repeat(A_, len(A_ ) ) else: assert len(A_ ) == len(A_ ) __magic_name__ = iter(A_ ) return np.array([estimator(int(A_ ), int(A_ ), A_ ) for n, c in zip(A_, A_ )] )
88
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
0
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _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 MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __magic_name__ : def __init__( self : Union[str, Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple=2 ,_UpperCAmelCase : Optional[int]=32 ,_UpperCAmelCase : Any=16 ,_UpperCAmelCase : Tuple=3 ,_UpperCAmelCase : Any=True ,_UpperCAmelCase : List[Any]=True ,_UpperCAmelCase : Union[str, Any]=32 ,_UpperCAmelCase : Optional[int]=4 ,_UpperCAmelCase : str=[0, 1, 2, 3] ,_UpperCAmelCase : Optional[Any]=4 ,_UpperCAmelCase : int=37 ,_UpperCAmelCase : int="gelu" ,_UpperCAmelCase : Tuple=0.1 ,_UpperCAmelCase : Dict=0.1 ,_UpperCAmelCase : List[Any]=0.02 ,_UpperCAmelCase : str=3 ,_UpperCAmelCase : Dict=[1, 384, 24, 24] ,_UpperCAmelCase : str=True ,_UpperCAmelCase : Any=None ,): _a : Optional[Any] = parent _a : Any = batch_size _a : str = image_size _a : Any = patch_size _a : Dict = num_channels _a : int = is_training _a : str = use_labels _a : List[Any] = hidden_size _a : Dict = num_hidden_layers _a : int = backbone_out_indices _a : Any = num_attention_heads _a : Dict = intermediate_size _a : Dict = hidden_act _a : Optional[int] = hidden_dropout_prob _a : Dict = attention_probs_dropout_prob _a : Union[str, Any] = initializer_range _a : Tuple = num_labels _a : Any = backbone_featmap_shape _a : Any = scope _a : Dict = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) _a : List[str] = (image_size // patch_size) ** 2 _a : Tuple = num_patches + 1 def __lowercase ( self : Optional[Any] ): _a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Dict = None if self.use_labels: _a : Optional[int] = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) _a : Any = self.get_config() return config, pixel_values, labels def __lowercase ( self : Optional[int] ): _a : Union[str, Any] = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [96, 192, 384, 768], 'num_groups': 2, } return DPTConfig( 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 ,backbone_out_indices=self.backbone_out_indices ,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 ,is_hybrid=self.is_hybrid ,backbone_config=_UpperCAmelCase ,backbone_featmap_shape=self.backbone_featmap_shape ,) def __lowercase ( self : Any ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[int] ): _a : Tuple = DPTModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Optional[int] = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self : str ,_UpperCAmelCase : Dict ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Union[str, Any] ): _a : Dict = self.num_labels _a : List[Any] = DPTForDepthEstimation(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Union[str, Any] = model(_UpperCAmelCase ) self.parent.assertEqual(result.predicted_depth.shape ,(self.batch_size, self.image_size, self.image_size) ) def __lowercase ( self : str ,_UpperCAmelCase : str ,_UpperCAmelCase : str ,_UpperCAmelCase : str ): _a : Union[str, Any] = self.num_labels _a : Union[str, Any] = DPTForSemanticSegmentation(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Tuple = model(_UpperCAmelCase ,labels=_UpperCAmelCase ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __lowercase ( self : Dict ): _a : Dict = self.prepare_config_and_inputs() _a , _a , _a : Any = config_and_inputs _a : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __magic_name__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : List[Any] = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () lowerCAmelCase : Tuple = ( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) lowerCAmelCase : Dict = False lowerCAmelCase : Any = False lowerCAmelCase : Optional[Any] = False def __lowercase ( self : Optional[int] ): _a : Union[str, Any] = DPTModelTester(self ) _a : List[Any] = ConfigTester(self ,config_class=_UpperCAmelCase ,has_text_modality=_UpperCAmelCase ,hidden_size=37 ) def __lowercase ( self : Dict ): self.config_tester.run_common_tests() @unittest.skip(reason='DPT does not use inputs_embeds' ) def __lowercase ( self : List[Any] ): pass def __lowercase ( self : str ): _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : str = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) _a : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase ,nn.Linear ) ) def __lowercase ( self : Dict ): _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : str = model_class(_UpperCAmelCase ) _a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : str = [*signature.parameters.keys()] _a : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_UpperCAmelCase ) def __lowercase ( self : Any ): _a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __lowercase ( self : List[str] ): _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*_UpperCAmelCase ) def __lowercase ( self : Optional[int] ): _a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase ) def __lowercase ( self : str ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue _a , _a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() _a : Optional[Any] = True if model_class in get_values(_UpperCAmelCase ): continue _a : List[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.train() _a : int = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : str = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : Optional[Any] ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue _a , _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _a : Optional[int] = False _a : Optional[int] = True if model_class in get_values(_UpperCAmelCase ) or not model_class.supports_gradient_checkpointing: continue _a : Any = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.gradient_checkpointing_enable() model.train() _a : Optional[Any] = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : str = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : Optional[Any] ): _a , _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : List[str] = _config_zero_init(_UpperCAmelCase ) for model_class in self.all_model_classes: _a : Optional[Any] = model_class(config=_UpperCAmelCase ) # Skip the check for the backbone _a : Optional[Any] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": _a : int = [F"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue 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""" ,) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase ( self : Tuple ): pass @slow def __lowercase ( self : Tuple ): for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: _a : int = DPTModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowercase ( self : str ): # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type _a , _a : Any = self.model_tester.prepare_config_and_inputs_for_common() _a : int = 'add' with self.assertRaises(_UpperCAmelCase ): _a : Dict = DPTForDepthEstimation(_UpperCAmelCase ) def __lowerCamelCase ( ) -> Tuple: _a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision @slow class __magic_name__ ( unittest.TestCase ): def __lowercase ( self : str ): _a : Optional[int] = DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas' ) _a : List[Any] = DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas' ).to(_UpperCAmelCase ) _a : Optional[int] = prepare_img() _a : str = image_processor(images=_UpperCAmelCase ,return_tensors='pt' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): _a : int = model(**_UpperCAmelCase ) _a : Union[str, Any] = outputs.predicted_depth # verify the predicted depth _a : List[str] = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape ,_UpperCAmelCase ) _a : Optional[Any] = torch.tensor( [[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 ,_UpperCAmelCase ,atol=1E-4 ) )
89
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
0
def lowerCamelCase_ ( UpperCamelCase__ : int ) -> list: """simple docstring""" __lowerCamelCase = int(UpperCamelCase__ ) if n_element < 1: __lowerCamelCase = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = (0, 0, 0) __lowerCamelCase = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": __A = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") __A = hamming(int(n)) print("-----------------------------------------------------") print(f'''The list with nth numbers is: {hamming_numbers}''') print("-----------------------------------------------------")
90
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : int = { """speechbrain/m-ctc-t-large""": """https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json""", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "mctct" def __init__( self : Union[str, Any] , lowercase_ : str=8065 , lowercase_ : Optional[Any]=1536 , lowercase_ : str=36 , lowercase_ : List[str]=6144 , lowercase_ : Optional[Any]=4 , lowercase_ : Optional[Any]=384 , lowercase_ : Tuple=920 , lowercase_ : Any=1e-5 , lowercase_ : Optional[Any]=0.3 , lowercase_ : Any="relu" , lowercase_ : Any=0.02 , lowercase_ : Dict=0.3 , lowercase_ : int=0.3 , lowercase_ : Union[str, Any]=1 , lowercase_ : Union[str, Any]=0 , lowercase_ : Union[str, Any]=2 , lowercase_ : Union[str, Any]=1 , lowercase_ : List[str]=0.3 , lowercase_ : Optional[int]=1 , lowercase_ : Dict=(7,) , lowercase_ : Union[str, Any]=(3,) , lowercase_ : Tuple=80 , lowercase_ : Union[str, Any]=1 , lowercase_ : Any=None , lowercase_ : Any="sum" , lowercase_ : List[Any]=False , **lowercase_ : Any , ): '''simple docstring''' super().__init__(**lowercase_ , pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : str = vocab_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = attention_head_dim SCREAMING_SNAKE_CASE_ : int = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Union[str, Any] = layerdrop SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = pad_token_id SCREAMING_SNAKE_CASE_ : Tuple = bos_token_id SCREAMING_SNAKE_CASE_ : int = eos_token_id SCREAMING_SNAKE_CASE_ : Optional[Any] = conv_glu_dim SCREAMING_SNAKE_CASE_ : List[str] = conv_dropout SCREAMING_SNAKE_CASE_ : Optional[Any] = num_conv_layers SCREAMING_SNAKE_CASE_ : Tuple = input_feat_per_channel SCREAMING_SNAKE_CASE_ : Optional[int] = input_channels SCREAMING_SNAKE_CASE_ : List[str] = conv_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = ctc_loss_reduction SCREAMING_SNAKE_CASE_ : str = ctc_zero_infinity # prevents config testing fail with exporting to json SCREAMING_SNAKE_CASE_ : Optional[Any] = list(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = list(lowercase_) if len(self.conv_kernel) != self.num_conv_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.conv_kernel)` == `config.num_conv_layers` ''' F'but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, ' F'`config.num_conv_layers = {self.num_conv_layers}`.')
91
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
0
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available UpperCamelCase__ = logging.getLogger(__name__) @dataclass class a__ : _a : str _a : List[str] _a : Optional[List[str]] @dataclass class a__ : _a : List[int] _a : List[int] _a : Optional[List[int]] = None _a : Optional[List[int]] = None class a__ ( snake_case__ ): _a : Optional[int] = """train""" _a : int = """dev""" _a : Tuple = """test""" class a__ : @staticmethod def __SCREAMING_SNAKE_CASE( _A , _A ): """simple docstring""" raise NotImplementedError @staticmethod def __SCREAMING_SNAKE_CASE( _A ): """simple docstring""" raise NotImplementedError @staticmethod def __SCREAMING_SNAKE_CASE( _A , _A , _A , _A , _A=False , _A="[CLS]" , _A=1 , _A="[SEP]" , _A=False , _A=False , _A=0 , _A=0 , _A=-1_0_0 , _A=0 , _A=True , ): """simple docstring""" __lowerCAmelCase = {label: i for i, label in enumerate(_A )} __lowerCAmelCase = [] for ex_index, example in enumerate(_A ): if ex_index % 1_0_0_0_0 == 0: logger.info("Writing example %d of %d" , _A , len(_A ) ) __lowerCAmelCase = [] __lowerCAmelCase = [] for word, label in zip(example.words , example.labels ): __lowerCAmelCase = tokenizer.tokenize(_A ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(_A ) > 0: tokens.extend(_A ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_A ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCAmelCase = tokenizer.num_special_tokens_to_add() if len(_A ) > max_seq_length - special_tokens_count: __lowerCAmelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCAmelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCAmelCase = [sequence_a_segment_id] * len(_A ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCAmelCase = [cls_token] + tokens __lowerCAmelCase = [pad_token_label_id] + label_ids __lowerCAmelCase = [cls_token_segment_id] + segment_ids __lowerCAmelCase = tokenizer.convert_tokens_to_ids(_A ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCAmelCase = [1 if mask_padding_with_zero else 0] * len(_A ) # Zero-pad up to the sequence length. __lowerCAmelCase = max_seq_length - len(_A ) if pad_on_left: __lowerCAmelCase = ([pad_token] * padding_length) + input_ids __lowerCAmelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCAmelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCAmelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(_A ) == max_seq_length assert len(_A ) == max_seq_length assert len(_A ) == max_seq_length assert len(_A ) == max_seq_length if ex_index < 5: logger.info("*** Example ***" ) logger.info("guid: %s" , example.guid ) logger.info("tokens: %s" , " ".join([str(_A ) for x in tokens] ) ) logger.info("input_ids: %s" , " ".join([str(_A ) for x in input_ids] ) ) logger.info("input_mask: %s" , " ".join([str(_A ) for x in input_mask] ) ) logger.info("segment_ids: %s" , " ".join([str(_A ) for x in segment_ids] ) ) logger.info("label_ids: %s" , " ".join([str(_A ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCAmelCase = None features.append( InputFeatures( input_ids=_A , attention_mask=_A , token_type_ids=_A , label_ids=_A ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class a__ ( snake_case__ ): _a : List[InputFeatures] _a : int = nn.CrossEntropyLoss().ignore_index def __init__( self , _A , _A , _A , _A , _A , _A = None , _A=False , _A = Split.train , ): """simple docstring""" __lowerCAmelCase = os.path.join( _A , "cached_{}_{}_{}".format(mode.value , tokenizer.__class__.__name__ , str(_A ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCAmelCase = cached_features_file + ".lock" with FileLock(_A ): if os.path.exists(_A ) and not overwrite_cache: logger.info(f"""Loading features from cached file {cached_features_file}""" ) __lowerCAmelCase = torch.load(_A ) else: logger.info(f"""Creating features from dataset file at {data_dir}""" ) __lowerCAmelCase = token_classification_task.read_examples_from_file(_A , _A ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCAmelCase = token_classification_task.convert_examples_to_features( _A , _A , _A , _A , cls_token_at_end=bool(model_type in ["xlnet"] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["xlnet"] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_A , pad_on_left=bool(tokenizer.padding_side == "left" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"""Saving features into cached file {cached_features_file}""" ) torch.save(self.features , _A ) def __len__( self ): """simple docstring""" return len(self.features ) def __getitem__( self , _A ): """simple docstring""" return self.features[i] if is_tf_available(): import tensorflow as tf class a__ : _a : List[InputFeatures] _a : int = -1_0_0 def __init__( self , _A , _A , _A , _A , _A , _A = None , _A=False , _A = Split.train , ): """simple docstring""" __lowerCAmelCase = token_classification_task.read_examples_from_file(_A , _A ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCAmelCase = token_classification_task.convert_examples_to_features( _A , _A , _A , _A , cls_token_at_end=bool(model_type in ["xlnet"] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["xlnet"] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_A , pad_on_left=bool(tokenizer.padding_side == "left" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCAmelCase = tf.data.Dataset.from_generator( _A , ({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa) , ( {"input_ids": tf.TensorShape([None] ), "attention_mask": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCAmelCase = tf.data.Dataset.from_generator( _A , ({"input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa}, tf.intaa) , ( { "input_ids": tf.TensorShape([None] ), "attention_mask": tf.TensorShape([None] ), "token_type_ids": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self ): """simple docstring""" return len(self.features ) def __getitem__( self , _A ): """simple docstring""" return self.features[i]
92
"""simple docstring""" import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
0
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowercase : Any = logging.get_logger(__name__) _lowercase : int = {"vocab_file": "spiece.model"} _lowercase : List[str] = { "vocab_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", } } # TODO(PVP) - this should be removed in Transformers v5 _lowercase : Optional[int] = { "t5-small": 5_1_2, "t5-base": 5_1_2, "t5-large": 5_1_2, "t5-3b": 5_1_2, "t5-11b": 5_1_2, } _lowercase : Tuple = "▁" class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE=1_00 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: lowercase_ : str = [F'''<extra_id_{i}>''' for i in range(__SCREAMING_SNAKE_CASE )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens lowercase_ : List[Any] = len(set(filter(lambda __SCREAMING_SNAKE_CASE : bool('''extra_id''' in str(__SCREAMING_SNAKE_CASE ) ) , __SCREAMING_SNAKE_CASE ) ) ) if extra_tokens != extra_ids: raise ValueError( F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( F'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) lowercase_ : Tuple = legacy lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , extra_ids=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , legacy=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : str = vocab_file lowercase_ : Union[str, Any] = extra_ids lowercase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) @staticmethod def _snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: lowercase_ : int = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' F''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' F''' {pretrained_model_name_or_path} automatically truncating your input to''' F''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' F''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , __SCREAMING_SNAKE_CASE , ) return max_model_length @property def _snake_case ( self ): """simple docstring""" return self.sp_model.get_piece_size() + self._extra_ids def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] return ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self ): """simple docstring""" return list( set(filter(lambda __SCREAMING_SNAKE_CASE : bool(re.search(R'''<extra_id_\d+>''' , __SCREAMING_SNAKE_CASE ) ) is not None , self.additional_special_tokens ) ) ) def _snake_case ( self ): """simple docstring""" return [self._convert_token_to_id(__SCREAMING_SNAKE_CASE ) for token in self.get_sentinel_tokens()] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if len(__SCREAMING_SNAKE_CASE ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : int = self._add_eos_if_not_present(__SCREAMING_SNAKE_CASE ) if token_ids_a is None: return token_ids_a else: lowercase_ : str = self._add_eos_if_not_present(__SCREAMING_SNAKE_CASE ) return token_ids_a + token_ids_a def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : Any = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Union[str, Any] = {} lowercase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if not self.legacy: lowercase_ : Any = SPIECE_UNDERLINE + text.replace(__SCREAMING_SNAKE_CASE , ''' ''' ) return super().tokenize(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if not self.legacy: lowercase_ : Optional[int] = text.startswith(__SCREAMING_SNAKE_CASE ) if is_first: lowercase_ : List[Any] = text[1:] lowercase_ : Dict = self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(__SCREAMING_SNAKE_CASE ): lowercase_ : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token.startswith('''<extra_id_''' ): lowercase_ : List[str] = re.match(R'''<extra_id_(\d+)>''' , __SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index < self.sp_model.get_piece_size(): lowercase_ : List[str] = self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) else: lowercase_ : Optional[int] = F'''<extra_id_{self.vocab_size - 1 - index}>''' return token def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = [] lowercase_ : str = '''''' lowercase_ : List[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(__SCREAMING_SNAKE_CASE ) + token lowercase_ : List[Any] = True lowercase_ : Union[str, Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = False out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : List[Any] = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[Any] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
93
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available snake_case : Union[str, Any] = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : List[str] = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Optional[Any] = ['''FlaxSpeechEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys snake_case : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
94
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
0
def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" return credit_card_number.startswith(("34", "35", "37", "4", "5", "6") ) def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : Tuple =credit_card_number a__ : Union[str, Any] =0 a__ : List[str] =len(SCREAMING_SNAKE_CASE ) - 2 for i in range(SCREAMING_SNAKE_CASE , -1 , -2 ): # double the value of every second digit a__ : List[Any] =int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 a__ : List[str] =cc_number[:i] + str(SCREAMING_SNAKE_CASE ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(SCREAMING_SNAKE_CASE ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : List[Any] =f'''{credit_card_number} is an invalid credit card number because''' if not credit_card_number.isdigit(): print(f'''{error_message} it has nonnumerical characters.''' ) return False if not 13 <= len(SCREAMING_SNAKE_CASE ) <= 16: print(f'''{error_message} of its length.''' ) return False if not validate_initial_digits(SCREAMING_SNAKE_CASE ): print(f'''{error_message} of its first two digits.''' ) return False if not luhn_validation(SCREAMING_SNAKE_CASE ): print(f'''{error_message} it fails the Luhn check.''' ) return False print(f'''{credit_card_number} is a valid credit card number.''' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("""4111111111111111""") validate_credit_card_number("""32323""")
95
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" import fire from utils import calculate_rouge, save_json def _snake_case ( lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): _lowerCamelCase : Dict = [x.strip() for x in open(lowercase__ ).readlines()] _lowerCamelCase : int = [x.strip() for x in open(lowercase__ ).readlines()][: len(lowercase__ )] _lowerCamelCase : int = calculate_rouge(lowercase__ , lowercase__ , **lowercase__ ) if save_path is not None: save_json(lowercase__ , lowercase__ , indent=lowercase__ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
96
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
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, ) __snake_case = { '''configuration_whisper''': ['''WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WhisperConfig''', '''WhisperOnnxConfig'''], '''feature_extraction_whisper''': ['''WhisperFeatureExtractor'''], '''processing_whisper''': ['''WhisperProcessor'''], '''tokenization_whisper''': ['''WhisperTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''WhisperTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''WhisperForConditionalGeneration''', '''WhisperModel''', '''WhisperPreTrainedModel''', '''WhisperForAudioClassification''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWhisperForConditionalGeneration''', '''TFWhisperModel''', '''TFWhisperPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''FlaxWhisperForConditionalGeneration''', '''FlaxWhisperModel''', '''FlaxWhisperPreTrainedModel''', '''FlaxWhisperForAudioClassification''', ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
97
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
0
"""simple docstring""" import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class snake_case ( __UpperCAmelCase ): """simple docstring""" def __init__( self : Dict ): UpperCAmelCase__ = [] def __lowerCAmelCase ( self : int ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[Any] ,**lowerCamelCase__ : int ): self.events.append('on_init_end' ) def __lowerCAmelCase ( self : Optional[Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Any ,**lowerCamelCase__ : Optional[Any] ): self.events.append('on_train_begin' ) def __lowerCAmelCase ( self : Dict ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : int ,**lowerCamelCase__ : int ): self.events.append('on_train_end' ) def __lowerCAmelCase ( self : str ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Any ,**lowerCamelCase__ : Optional[Any] ): self.events.append('on_epoch_begin' ) def __lowerCAmelCase ( self : str ,lowerCamelCase__ : Dict ,lowerCamelCase__ : str ,lowerCamelCase__ : Dict ,**lowerCamelCase__ : List[Any] ): self.events.append('on_epoch_end' ) def __lowerCAmelCase ( self : Tuple ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : str ,lowerCamelCase__ : Union[str, Any] ,**lowerCamelCase__ : Union[str, Any] ): self.events.append('on_step_begin' ) def __lowerCAmelCase ( self : str ,lowerCamelCase__ : Any ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[str] ,**lowerCamelCase__ : Optional[Any] ): self.events.append('on_step_end' ) def __lowerCAmelCase ( self : Optional[int] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : List[str] ,**lowerCamelCase__ : List[str] ): self.events.append('on_evaluate' ) def __lowerCAmelCase ( self : Any ,lowerCamelCase__ : int ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Union[str, Any] ,**lowerCamelCase__ : Union[str, Any] ): self.events.append('on_predict' ) def __lowerCAmelCase ( self : Tuple ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Any ,**lowerCamelCase__ : Optional[Any] ): self.events.append('on_save' ) def __lowerCAmelCase ( self : Tuple ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Optional[int] ,**lowerCamelCase__ : Union[str, Any] ): self.events.append('on_log' ) def __lowerCAmelCase ( self : Dict ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[Any] ,**lowerCamelCase__ : Optional[int] ): self.events.append('on_prediction_step' ) @require_torch class snake_case ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ): UpperCAmelCase__ = tempfile.mkdtemp() def __lowerCAmelCase ( self : int ): shutil.rmtree(self.output_dir ) def __lowerCAmelCase ( self : Optional[Any] ,lowerCamelCase__ : Optional[Any]=0 ,lowerCamelCase__ : str=0 ,lowerCamelCase__ : List[str]=64 ,lowerCamelCase__ : Tuple=64 ,lowerCamelCase__ : Union[str, Any]=None ,lowerCamelCase__ : Any=False ,**lowerCamelCase__ : List[Any] ): # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. UpperCAmelCase__ = RegressionDataset(length=lowerCamelCase__ ) UpperCAmelCase__ = RegressionDataset(length=lowerCamelCase__ ) UpperCAmelCase__ = RegressionModelConfig(a=lowerCamelCase__ ,b=lowerCamelCase__ ) UpperCAmelCase__ = RegressionPreTrainedModel(lowerCamelCase__ ) UpperCAmelCase__ = TrainingArguments(self.output_dir ,disable_tqdm=lowerCamelCase__ ,report_to=[] ,**lowerCamelCase__ ) return Trainer( lowerCamelCase__ ,lowerCamelCase__ ,train_dataset=lowerCamelCase__ ,eval_dataset=lowerCamelCase__ ,callbacks=lowerCamelCase__ ,) def __lowerCAmelCase ( self : Optional[int] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[str] ): self.assertEqual(len(lowerCamelCase__ ) ,len(lowerCamelCase__ ) ) # Order doesn't matter UpperCAmelCase__ = sorted(lowerCamelCase__ ,key=lambda lowerCamelCase__ : cb.__name__ if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else cb.__class__.__name__ ) UpperCAmelCase__ = sorted(lowerCamelCase__ ,key=lambda lowerCamelCase__ : cb.__name__ if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else cb.__class__.__name__ ) for cba, cba in zip(lowerCamelCase__ ,lowerCamelCase__ ): if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) and isinstance(lowerCamelCase__ ,lowerCamelCase__ ): self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ) and not isinstance(lowerCamelCase__ ,lowerCamelCase__ ): self.assertEqual(lowerCamelCase__ ,cba.__class__ ) elif not isinstance(lowerCamelCase__ ,lowerCamelCase__ ) and isinstance(lowerCamelCase__ ,lowerCamelCase__ ): self.assertEqual(cba.__class__ ,lowerCamelCase__ ) else: self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def __lowerCAmelCase ( self : List[str] ,lowerCamelCase__ : Optional[int] ): UpperCAmelCase__ = ['on_init_end', 'on_train_begin'] UpperCAmelCase__ = 0 UpperCAmelCase__ = len(trainer.get_eval_dataloader() ) UpperCAmelCase__ = ['on_prediction_step'] * len(trainer.get_eval_dataloader() ) + ['on_log', 'on_evaluate'] for _ in range(trainer.state.num_train_epochs ): expected_events.append('on_epoch_begin' ) for _ in range(lowerCamelCase__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('on_log' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('on_save' ) expected_events.append('on_epoch_end' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __lowerCAmelCase ( self : Union[str, Any] ): UpperCAmelCase__ = self.get_trainer() UpperCAmelCase__ = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) # Callbacks passed at init are added to the default callbacks UpperCAmelCase__ = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(lowerCamelCase__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback UpperCAmelCase__ = self.get_trainer(disable_tqdm=lowerCamelCase__ ) UpperCAmelCase__ = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) def __lowerCAmelCase ( self : Optional[int] ): UpperCAmelCase__ = DEFAULT_CALLBACKS.copy() + [ProgressCallback] UpperCAmelCase__ = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(lowerCamelCase__ ) expected_callbacks.remove(lowerCamelCase__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) UpperCAmelCase__ = self.get_trainer() UpperCAmelCase__ = trainer.pop_callback(lowerCamelCase__ ) self.assertEqual(cb.__class__ ,lowerCamelCase__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) trainer.add_callback(lowerCamelCase__ ) expected_callbacks.insert(0 ,lowerCamelCase__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) # We can also add, pop, or remove by instance UpperCAmelCase__ = self.get_trainer() UpperCAmelCase__ = trainer.callback_handler.callbacks[0] trainer.remove_callback(lowerCamelCase__ ) expected_callbacks.remove(lowerCamelCase__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) UpperCAmelCase__ = self.get_trainer() UpperCAmelCase__ = trainer.callback_handler.callbacks[0] UpperCAmelCase__ = trainer.pop_callback(lowerCamelCase__ ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) trainer.add_callback(lowerCamelCase__ ) expected_callbacks.insert(0 ,lowerCamelCase__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks ,lowerCamelCase__ ) def __lowerCAmelCase ( self : Tuple ): import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='ignore' ,category=lowerCamelCase__ ) UpperCAmelCase__ = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() UpperCAmelCase__ = trainer.callback_handler.callbacks[-2].events self.assertEqual(lowerCamelCase__ ,self.get_expected_events(lowerCamelCase__ ) ) # Independent log/save/eval UpperCAmelCase__ = self.get_trainer(callbacks=[MyTestTrainerCallback] ,logging_steps=5 ) trainer.train() UpperCAmelCase__ = trainer.callback_handler.callbacks[-2].events self.assertEqual(lowerCamelCase__ ,self.get_expected_events(lowerCamelCase__ ) ) UpperCAmelCase__ = self.get_trainer(callbacks=[MyTestTrainerCallback] ,save_steps=5 ) trainer.train() UpperCAmelCase__ = trainer.callback_handler.callbacks[-2].events self.assertEqual(lowerCamelCase__ ,self.get_expected_events(lowerCamelCase__ ) ) UpperCAmelCase__ = self.get_trainer(callbacks=[MyTestTrainerCallback] ,eval_steps=5 ,evaluation_strategy='steps' ) trainer.train() UpperCAmelCase__ = trainer.callback_handler.callbacks[-2].events self.assertEqual(lowerCamelCase__ ,self.get_expected_events(lowerCamelCase__ ) ) UpperCAmelCase__ = self.get_trainer(callbacks=[MyTestTrainerCallback] ,evaluation_strategy='epoch' ) trainer.train() UpperCAmelCase__ = trainer.callback_handler.callbacks[-2].events self.assertEqual(lowerCamelCase__ ,self.get_expected_events(lowerCamelCase__ ) ) # A bit of everything UpperCAmelCase__ = self.get_trainer( callbacks=[MyTestTrainerCallback] ,logging_steps=3 ,save_steps=10 ,eval_steps=5 ,evaluation_strategy='steps' ,) trainer.train() UpperCAmelCase__ = trainer.callback_handler.callbacks[-2].events self.assertEqual(lowerCamelCase__ ,self.get_expected_events(lowerCamelCase__ ) ) # warning should be emitted for duplicated callbacks with patch('transformers.trainer_callback.logger.warning' ) as warn_mock: UpperCAmelCase__ = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] ,) assert str(lowerCamelCase__ ) in warn_mock.call_args[0][0]
98
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
0
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class A__ ( __UpperCAmelCase ): """simple docstring""" def __lowercase ( self) -> Optional[Any]: '''simple docstring''' return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : str = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} return Dataset.from_dict(lowercase) def __lowercase ( self) -> int: '''simple docstring''' a__ : Optional[Any] = self._create_example_records() a__ : Dict = Dataset.from_list(lowercase) self.assertListEqual(dset.column_names , ['col_1', 'col_2']) for i, r in enumerate(lowercase): self.assertDictEqual(lowercase , example_records[i]) def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : Any = self._create_example_records() a__ : Optional[int] = Dataset.from_list(lowercase) a__ : str = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]}) self.assertEqual(dset.info , dset_from_dict.info) def __lowercase ( self) -> Optional[int]: # checks what happens with missing columns '''simple docstring''' a__ : int = [{'col_1': 1}, {'col_2': 'x'}] a__ : int = Dataset.from_list(lowercase) self.assertDictEqual(dset[0] , {'col_1': 1}) self.assertDictEqual(dset[1] , {'col_1': None}) # NB: first record is used for columns def __lowercase ( self) -> int: # checks if the type can be inferred from the second record '''simple docstring''' a__ : Union[str, Any] = [{'col_1': []}, {'col_1': [1, 2]}] a__ : Any = Dataset.from_list(lowercase) self.assertEqual(dset.info.features['col_1'] , Sequence(Value('int64'))) def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : List[str] = Dataset.from_list([]) self.assertEqual(len(lowercase) , 0) self.assertListEqual(dset.column_names , [])
99
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP __magic_name__ = logging.get_logger(__name__) # pylint: disable=invalid-name __magic_name__ = "\n Examples:\n ```py\n >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\")\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"red cat, 4k photo\"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> negative_image_emb = out.negative_image_embeds\n\n >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\")\n >>> pipe.to(\"cuda\")\n\n >>> image = pipe(\n ... prompt,\n ... image_embeds=image_emb,\n ... negative_image_embeds=negative_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... ).images\n\n >>> image[0].save(\"cat.png\")\n ```\n" def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=8 ): __SCREAMING_SNAKE_CASE = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 __SCREAMING_SNAKE_CASE = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ): super().__init__() self.register_modules( text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , movq=lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels) - 1) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): if latents is None: __SCREAMING_SNAKE_CASE = randn_tensor(lowerCAmelCase__ , generator=lowerCAmelCase__ , device=lowerCAmelCase__ , dtype=lowerCAmelCase__) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") __SCREAMING_SNAKE_CASE = latents.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , ): __SCREAMING_SNAKE_CASE = len(lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else 1 # get prompt text embeddings __SCREAMING_SNAKE_CASE = self.tokenizer( lowerCAmelCase__ , padding="""max_length""" , truncation=lowerCAmelCase__ , max_length=7_7 , return_attention_mask=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = text_inputs.input_ids __SCREAMING_SNAKE_CASE = self.tokenizer(lowerCAmelCase__ , padding="""longest""" , return_tensors="""pt""").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f" {self.tokenizer.model_max_length} tokens: {removed_text}") __SCREAMING_SNAKE_CASE = text_input_ids.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = text_inputs.attention_mask.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self.text_encoder( input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = prompt_embeds.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = text_encoder_hidden_states.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = text_mask.repeat_interleave(lowerCAmelCase__ , dim=0) if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE = 42 if negative_prompt is None: __SCREAMING_SNAKE_CASE = [""""""] * batch_size elif type(lowerCAmelCase__) is not type(lowerCAmelCase__): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(lowerCAmelCase__)} !=" f" {type(lowerCAmelCase__)}.") elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = [negative_prompt] elif batch_size != len(lowerCAmelCase__): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(lowerCAmelCase__)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""") else: __SCREAMING_SNAKE_CASE = negative_prompt __SCREAMING_SNAKE_CASE = self.tokenizer( lowerCAmelCase__ , padding="""max_length""" , max_length=7_7 , truncation=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = uncond_input.input_ids.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = uncond_input.attention_mask.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self.text_encoder( input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __SCREAMING_SNAKE_CASE = negative_prompt_embeds.shape[1] __SCREAMING_SNAKE_CASE = negative_prompt_embeds.repeat(1 , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = negative_prompt_embeds.view(batch_size * num_images_per_prompt , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = uncond_text_encoder_hidden_states.shape[1] __SCREAMING_SNAKE_CASE = uncond_text_encoder_hidden_states.repeat(1 , lowerCAmelCase__ , 1) __SCREAMING_SNAKE_CASE = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , lowerCAmelCase__ , -1) __SCREAMING_SNAKE_CASE = uncond_text_mask.repeat_interleave(lowerCAmelCase__ , dim=0) # done duplicates # 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 = torch.cat([negative_prompt_embeds, prompt_embeds]) __SCREAMING_SNAKE_CASE = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]) __SCREAMING_SNAKE_CASE = torch.cat([uncond_text_mask, text_mask]) return prompt_embeds, text_encoder_hidden_states, text_mask def snake_case_ ( self , lowerCAmelCase__=0): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""") __SCREAMING_SNAKE_CASE = torch.device(f"cuda:{gpu_id}") __SCREAMING_SNAKE_CASE = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCAmelCase__ , lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__=0): if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0"""): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""") __SCREAMING_SNAKE_CASE = torch.device(f"cuda:{gpu_id}") if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCAmelCase__) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = cpu_offload_with_hook(lowerCAmelCase__ , lowerCAmelCase__ , prev_module_hook=lowerCAmelCase__) if self.safety_checker is not None: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = cpu_offload_with_hook(self.safety_checker , lowerCAmelCase__ , prev_module_hook=lowerCAmelCase__) # We'll offload the last model manually. __SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_ ( self): if not hasattr(self.unet , """_hf_hook"""): return self.device for module in self.unet.modules(): if ( hasattr(lowerCAmelCase__ , """_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() @replace_example_docstring(lowerCAmelCase__) def __call__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = 5_1_2 , lowerCAmelCase__ = 5_1_2 , lowerCAmelCase__ = 1_0_0 , lowerCAmelCase__ = 4.0 , lowerCAmelCase__ = 1 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = "pil" , lowerCAmelCase__ = True , ): if isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = 1 elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = len(lowerCAmelCase__) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase__)}") __SCREAMING_SNAKE_CASE = self._execution_device __SCREAMING_SNAKE_CASE = batch_size * num_images_per_prompt __SCREAMING_SNAKE_CASE = guidance_scale > 1.0 __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self._encode_prompt( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = torch.cat(lowerCAmelCase__ , dim=0) if isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = torch.cat(lowerCAmelCase__ , dim=0) if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0).to( dtype=prompt_embeds.dtype , device=lowerCAmelCase__) self.scheduler.set_timesteps(lowerCAmelCase__ , device=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = self.scheduler.timesteps __SCREAMING_SNAKE_CASE = self.unet.config.in_channels __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = get_new_h_w(lowerCAmelCase__ , lowerCAmelCase__ , self.movq_scale_factor) # create initial latent __SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCAmelCase__)): # expand the latents if we are doing classifier free guidance __SCREAMING_SNAKE_CASE = torch.cat([latents] * 2) if do_classifier_free_guidance else latents __SCREAMING_SNAKE_CASE = {"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds} __SCREAMING_SNAKE_CASE = self.unet( sample=lowerCAmelCase__ , timestep=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , added_cond_kwargs=lowerCAmelCase__ , return_dict=lowerCAmelCase__ , )[0] if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = noise_pred.chunk(2) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = variance_pred.chunk(2) __SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1) if not ( hasattr(self.scheduler.config , """variance_type""") and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1) # compute the previous noisy sample x_t -> x_t-1 __SCREAMING_SNAKE_CASE = self.scheduler.step( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , generator=lowerCAmelCase__ , ).prev_sample # post-processing __SCREAMING_SNAKE_CASE = self.movq.decode(lowerCAmelCase__ , force_not_quantize=lowerCAmelCase__)["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}") if output_type in ["np", "pil"]: __SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 __SCREAMING_SNAKE_CASE = image.clamp(0 , 1) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE = self.numpy_to_pil(lowerCAmelCase__) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase__)
100
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
def UpperCamelCase ( lowerCAmelCase__ = 1000 ): '''simple docstring''' lowercase = -1 lowercase = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c lowercase = (n * n - 2 * a * n) // (2 * n - 2 * a) lowercase = n - a - b if c * c == (a * a + b * b): lowercase = a * b * c if candidate >= product: lowercase = candidate return product if __name__ == "__main__": print(F'{solution() = }')
101
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = pipeline( 'document-question-answering' , model='naver-clova-ix/donut-base-finetuned-docvqa' , tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa' ) , feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
0
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class _UpperCAmelCase ( __snake_case ): '''simple docstring''' def __init__(self ): '''simple docstring''' self.test() def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : List[str] = 0 __snake_case : Tuple = False while not completed: if counter == 1: self.reset() __snake_case : Dict = self.advance() if not self.does_advance(a_ ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) __snake_case , __snake_case , __snake_case : Tuple = self.update(a_ ) counter += 1 if counter > 1_00_00: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE (self , a_=False ): '''simple docstring''' raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class _UpperCAmelCase ( __snake_case ): '''simple docstring''' def __init__(self , a_ ): '''simple docstring''' super(a_ , self ).__init__() if not isinstance(a_ , a_ ) or len(a_ ) == 0: raise ValueError(f"""`token_ids` has to be a non-empty list, but is {token_ids}.""" ) if any((not isinstance(a_ , a_ ) or token_id < 0) for token_id in token_ids ): raise ValueError(f"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.""" ) __snake_case : str = token_ids __snake_case : Optional[Any] = len(self.token_ids ) __snake_case : Dict = -1 # the index of the currently fulfilled step __snake_case : List[str] = False def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' if not isinstance(a_ , a_ ): raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(a_ )}""" ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' if not isinstance(a_ , a_ ): raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(a_ )}""" ) __snake_case : Optional[Any] = False __snake_case : Tuple = False __snake_case : Optional[Any] = False if self.does_advance(a_ ): self.fulfilled_idx += 1 __snake_case : Optional[Any] = True if self.fulfilled_idx == (self.seqlen - 1): __snake_case : List[str] = True __snake_case : Tuple = completed else: # failed to make progress. __snake_case : Union[str, Any] = True self.reset() return stepped, completed, reset def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = False __snake_case : Optional[int] = 0 def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return self.seqlen - (self.fulfilled_idx + 1) def SCREAMING_SNAKE_CASE (self , a_=False ): '''simple docstring''' __snake_case : Union[str, Any] = PhrasalConstraint(self.token_ids ) if stateful: __snake_case : List[Any] = self.seqlen __snake_case : str = self.fulfilled_idx __snake_case : Union[str, Any] = self.completed return new_constraint class _UpperCAmelCase : '''simple docstring''' def __init__(self , a_ , a_=True ): '''simple docstring''' __snake_case : List[str] = max([len(a_ ) for one in nested_token_ids] ) __snake_case : str = {} for token_ids in nested_token_ids: __snake_case : Optional[Any] = root for tidx, token_id in enumerate(a_ ): if token_id not in level: __snake_case : Optional[Any] = {} __snake_case : List[Any] = level[token_id] if no_subsets and self.has_subsets(a_ , a_ ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' f""" {nested_token_ids}.""" ) __snake_case : Any = root def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : int = self.trie for current_token in current_seq: __snake_case : str = start[current_token] __snake_case : Tuple = list(start.keys() ) return next_tokens def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : int = self.next_tokens(a_ ) return len(a_ ) == 0 def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : int = list(root.values() ) if len(a_ ) == 0: return 1 else: return sum([self.count_leaves(a_ ) for nn in next_nodes] ) def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : Optional[int] = self.count_leaves(a_ ) return len(a_ ) != leaf_count class _UpperCAmelCase ( __snake_case ): '''simple docstring''' def __init__(self , a_ ): '''simple docstring''' super(a_ , self ).__init__() if not isinstance(a_ , a_ ) or len(a_ ) == 0: raise ValueError(f"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" ) if any(not isinstance(a_ , a_ ) for token_ids in nested_token_ids ): raise ValueError(f"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.""" ) if any( any((not isinstance(a_ , a_ ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( f"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.""" ) __snake_case : Union[str, Any] = DisjunctiveTrie(a_ ) __snake_case : int = nested_token_ids __snake_case : List[Any] = self.trie.max_height __snake_case : Optional[Any] = [] __snake_case : List[Any] = False def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[Any] = self.trie.next_tokens(self.current_seq ) if len(a_ ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' if not isinstance(a_ , a_ ): raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(a_ )}""" ) __snake_case : List[Any] = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' if not isinstance(a_ , a_ ): raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(a_ )}""" ) __snake_case : Any = False __snake_case : int = False __snake_case : Optional[Any] = False if self.does_advance(a_ ): self.current_seq.append(a_ ) __snake_case : List[Any] = True else: __snake_case : Optional[Any] = True self.reset() __snake_case : Union[str, Any] = self.trie.reached_leaf(self.current_seq ) __snake_case : List[Any] = completed return stepped, completed, reset def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = False __snake_case : List[str] = [] def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def SCREAMING_SNAKE_CASE (self , a_=False ): '''simple docstring''' __snake_case : Optional[int] = DisjunctiveConstraint(self.token_ids ) if stateful: __snake_case : List[str] = self.seqlen __snake_case : Optional[Any] = self.current_seq __snake_case : Optional[int] = self.completed return new_constraint class _UpperCAmelCase : '''simple docstring''' def __init__(self , a_ ): '''simple docstring''' __snake_case : int = constraints # max # of steps required to fulfill a given constraint __snake_case : List[str] = max([c.seqlen for c in constraints] ) __snake_case : List[str] = len(a_ ) __snake_case : Optional[Any] = False self.init_state() def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Dict = [] __snake_case : List[str] = None __snake_case : Dict = [constraint.copy(stateful=a_ ) for constraint in self.constraints] def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" __snake_case : List[Any] = constraint.advance() if isinstance(a_ , a_ ): token_list.append(a_ ) elif isinstance(a_ , a_ ): token_list.extend(a_ ) else: __snake_case : Dict = self.inprogress_constraint.advance() if isinstance(a_ , a_ ): token_list.append(a_ ) elif isinstance(a_ , a_ ): token_list.extend(a_ ) if len(a_ ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint __snake_case , __snake_case : List[str] = self.add(a_ ) # the entire list of constraints are fulfilled if self.completed: break def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' if not isinstance(a_ , a_ ): raise ValueError(f"""`token_id` should be an `int`, but is `{token_id}`.""" ) __snake_case , __snake_case : Dict = False, False if self.completed: __snake_case : Dict = True __snake_case : Optional[Any] = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state __snake_case , __snake_case , __snake_case : Tuple = self.inprogress_constraint.update(a_ ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=a_ ) ) __snake_case : str = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) __snake_case : List[str] = None if len(self.pending_constraints ) == 0: # we're done! __snake_case : int = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(a_ ): __snake_case , __snake_case , __snake_case : Any = pending_constraint.update(a_ ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(a_ ) __snake_case : List[Any] = None if not complete and stepped: __snake_case : Tuple = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". __snake_case : str = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. __snake_case : Optional[Any] = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def SCREAMING_SNAKE_CASE (self , a_=True ): '''simple docstring''' __snake_case : List[Any] = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: __snake_case : List[str] = [ constraint.copy(stateful=a_ ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: __snake_case : int = self.inprogress_constraint.copy(stateful=a_ ) __snake_case : Optional[Any] = [constraint.copy() for constraint in self.pending_constraints] return new_state
102
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
0
from __future__ import annotations def UpperCamelCase( __UpperCamelCase : list ): if len(__UpperCamelCase ) == 0: return [] lowerCAmelCase_ , lowerCAmelCase_ : List[str] = min(__UpperCamelCase ), max(__UpperCamelCase ) lowerCAmelCase_ : List[Any] = int(max_value - min_value ) + 1 lowerCAmelCase_ : list[list] = [[] for _ in range(__UpperCamelCase )] for i in my_list: buckets[int(i - min_value )].append(__UpperCamelCase ) return [v for bucket in buckets for v in sorted(__UpperCamelCase )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
103
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : torch.FloatTensor class lowercase_ (nn.Module ): """simple docstring""" def __init__( self : str ,lowercase__ : Tuple=3 ,lowercase__ : List[str]=3 ,lowercase__ : str=("DownEncoderBlock2D",) ,lowercase__ : List[str]=(6_4,) ,lowercase__ : List[str]=2 ,lowercase__ : Optional[Any]=3_2 ,lowercase__ : List[str]="silu" ,lowercase__ : List[str]=True ,): super().__init__() __lowercase = layers_per_block __lowercase = torch.nn.Convad( lowercase__ ,block_out_channels[0] ,kernel_size=3 ,stride=1 ,padding=1 ,) __lowercase = None __lowercase = nn.ModuleList([] ) # down __lowercase = block_out_channels[0] for i, down_block_type in enumerate(lowercase__ ): __lowercase = output_channel __lowercase = block_out_channels[i] __lowercase = i == len(lowercase__ ) - 1 __lowercase = get_down_block( lowercase__ ,num_layers=self.layers_per_block ,in_channels=lowercase__ ,out_channels=lowercase__ ,add_downsample=not is_final_block ,resnet_eps=1e-6 ,downsample_padding=0 ,resnet_act_fn=lowercase__ ,resnet_groups=lowercase__ ,attention_head_dim=lowercase__ ,temb_channels=lowercase__ ,) self.down_blocks.append(lowercase__ ) # mid __lowercase = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=lowercase__ ,output_scale_factor=1 ,resnet_time_scale_shift='''default''' ,attention_head_dim=block_out_channels[-1] ,resnet_groups=lowercase__ ,temb_channels=lowercase__ ,) # out __lowercase = nn.GroupNorm(num_channels=block_out_channels[-1] ,num_groups=lowercase__ ,eps=1e-6 ) __lowercase = nn.SiLU() __lowercase = 2 * out_channels if double_z else out_channels __lowercase = nn.Convad(block_out_channels[-1] ,lowercase__ ,3 ,padding=1 ) __lowercase = False def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Any ): __lowercase = x __lowercase = self.conv_in(lowercase__ ) if self.training and self.gradient_checkpointing: def create_custom_forward(lowercase__ : List[Any] ): def custom_forward(*lowercase__ : Dict ): return module(*lowercase__ ) return custom_forward # down if is_torch_version('''>=''' ,'''1.11.0''' ): for down_block in self.down_blocks: __lowercase = torch.utils.checkpoint.checkpoint( create_custom_forward(lowercase__ ) ,lowercase__ ,use_reentrant=lowercase__ ) # middle __lowercase = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,lowercase__ ,use_reentrant=lowercase__ ) else: for down_block in self.down_blocks: __lowercase = torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__ ) ,lowercase__ ) # middle __lowercase = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) ,lowercase__ ) else: # down for down_block in self.down_blocks: __lowercase = down_block(lowercase__ ) # middle __lowercase = self.mid_block(lowercase__ ) # post-process __lowercase = self.conv_norm_out(lowercase__ ) __lowercase = self.conv_act(lowercase__ ) __lowercase = self.conv_out(lowercase__ ) return sample class lowercase_ (nn.Module ): """simple docstring""" def __init__( self : str ,lowercase__ : Optional[Any]=3 ,lowercase__ : Any=3 ,lowercase__ : Union[str, Any]=("UpDecoderBlock2D",) ,lowercase__ : Any=(6_4,) ,lowercase__ : str=2 ,lowercase__ : Optional[int]=3_2 ,lowercase__ : Tuple="silu" ,lowercase__ : Union[str, Any]="group" ,): super().__init__() __lowercase = layers_per_block __lowercase = nn.Convad( lowercase__ ,block_out_channels[-1] ,kernel_size=3 ,stride=1 ,padding=1 ,) __lowercase = None __lowercase = nn.ModuleList([] ) __lowercase = in_channels if norm_type == '''spatial''' else None # mid __lowercase = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=lowercase__ ,output_scale_factor=1 ,resnet_time_scale_shift='''default''' if norm_type == '''group''' else norm_type ,attention_head_dim=block_out_channels[-1] ,resnet_groups=lowercase__ ,temb_channels=lowercase__ ,) # up __lowercase = list(reversed(lowercase__ ) ) __lowercase = reversed_block_out_channels[0] for i, up_block_type in enumerate(lowercase__ ): __lowercase = output_channel __lowercase = reversed_block_out_channels[i] __lowercase = i == len(lowercase__ ) - 1 __lowercase = get_up_block( lowercase__ ,num_layers=self.layers_per_block + 1 ,in_channels=lowercase__ ,out_channels=lowercase__ ,prev_output_channel=lowercase__ ,add_upsample=not is_final_block ,resnet_eps=1e-6 ,resnet_act_fn=lowercase__ ,resnet_groups=lowercase__ ,attention_head_dim=lowercase__ ,temb_channels=lowercase__ ,resnet_time_scale_shift=lowercase__ ,) self.up_blocks.append(lowercase__ ) __lowercase = output_channel # out if norm_type == "spatial": __lowercase = SpatialNorm(block_out_channels[0] ,lowercase__ ) else: __lowercase = nn.GroupNorm(num_channels=block_out_channels[0] ,num_groups=lowercase__ ,eps=1e-6 ) __lowercase = nn.SiLU() __lowercase = nn.Convad(block_out_channels[0] ,lowercase__ ,3 ,padding=1 ) __lowercase = False def SCREAMING_SNAKE_CASE ( self : str ,lowercase__ : Optional[Any] ,lowercase__ : List[Any]=None ): __lowercase = z __lowercase = self.conv_in(lowercase__ ) __lowercase = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(lowercase__ : str ): def custom_forward(*lowercase__ : List[Any] ): return module(*lowercase__ ) return custom_forward if is_torch_version('''>=''' ,'''1.11.0''' ): # middle __lowercase = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,lowercase__ ,lowercase__ ,use_reentrant=lowercase__ ) __lowercase = sample.to(lowercase__ ) # up for up_block in self.up_blocks: __lowercase = torch.utils.checkpoint.checkpoint( create_custom_forward(lowercase__ ) ,lowercase__ ,lowercase__ ,use_reentrant=lowercase__ ) else: # middle __lowercase = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,lowercase__ ,lowercase__ ) __lowercase = sample.to(lowercase__ ) # up for up_block in self.up_blocks: __lowercase = torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__ ) ,lowercase__ ,lowercase__ ) else: # middle __lowercase = self.mid_block(lowercase__ ,lowercase__ ) __lowercase = sample.to(lowercase__ ) # up for up_block in self.up_blocks: __lowercase = up_block(lowercase__ ,lowercase__ ) # post-process if latent_embeds is None: __lowercase = self.conv_norm_out(lowercase__ ) else: __lowercase = self.conv_norm_out(lowercase__ ,lowercase__ ) __lowercase = self.conv_act(lowercase__ ) __lowercase = self.conv_out(lowercase__ ) return sample class lowercase_ (nn.Module ): """simple docstring""" def __init__( self : int ,lowercase__ : str ,lowercase__ : List[Any] ,lowercase__ : str ,lowercase__ : int=None ,lowercase__ : int="random" ,lowercase__ : Tuple=False ,lowercase__ : List[str]=True ): super().__init__() __lowercase = n_e __lowercase = vq_embed_dim __lowercase = beta __lowercase = legacy __lowercase = nn.Embedding(self.n_e ,self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e ,1.0 / self.n_e ) __lowercase = remap if self.remap is not None: self.register_buffer('''used''' ,torch.tensor(np.load(self.remap ) ) ) __lowercase = self.used.shape[0] __lowercase = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": __lowercase = self.re_embed __lowercase = self.re_embed + 1 print( F"Remapping {self.n_e} indices to {self.re_embed} indices. " F"Using {self.unknown_index} for unknown indices." ) else: __lowercase = n_e __lowercase = sane_index_shape def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : List[Any] ): __lowercase = inds.shape assert len(lowercase__ ) > 1 __lowercase = inds.reshape(ishape[0] ,-1 ) __lowercase = self.used.to(lowercase__ ) __lowercase = (inds[:, :, None] == used[None, None, ...]).long() __lowercase = match.argmax(-1 ) __lowercase = match.sum(2 ) < 1 if self.unknown_index == "random": __lowercase = torch.randint(0 ,self.re_embed ,size=new[unknown].shape ).to(device=new.device ) else: __lowercase = self.unknown_index return new.reshape(lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Any ): __lowercase = inds.shape assert len(lowercase__ ) > 1 __lowercase = inds.reshape(ishape[0] ,-1 ) __lowercase = self.used.to(lowercase__ ) if self.re_embed > self.used.shape[0]: # extra token __lowercase = 0 # simply set to zero __lowercase = torch.gather(used[None, :][inds.shape[0] * [0], :] ,1 ,lowercase__ ) return back.reshape(lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : Tuple ): # reshape z -> (batch, height, width, channel) and flatten __lowercase = z.permute(0 ,2 ,3 ,1 ).contiguous() __lowercase = z.view(-1 ,self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z __lowercase = torch.argmin(torch.cdist(lowercase__ ,self.embedding.weight ) ,dim=1 ) __lowercase = self.embedding(lowercase__ ).view(z.shape ) __lowercase = None __lowercase = None # compute loss for embedding if not self.legacy: __lowercase = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: __lowercase = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients __lowercase = z + (z_q - z).detach() # reshape back to match original input shape __lowercase = z_q.permute(0 ,3 ,1 ,2 ).contiguous() if self.remap is not None: __lowercase = min_encoding_indices.reshape(z.shape[0] ,-1 ) # add batch axis __lowercase = self.remap_to_used(lowercase__ ) __lowercase = min_encoding_indices.reshape(-1 ,1 ) # flatten if self.sane_index_shape: __lowercase = min_encoding_indices.reshape(z_q.shape[0] ,z_q.shape[2] ,z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : List[Any] ,lowercase__ : List[str] ): # shape specifying (batch, height, width, channel) if self.remap is not None: __lowercase = indices.reshape(shape[0] ,-1 ) # add batch axis __lowercase = self.unmap_to_all(lowercase__ ) __lowercase = indices.reshape(-1 ) # flatten again # get quantized latent vectors __lowercase = self.embedding(lowercase__ ) if shape is not None: __lowercase = z_q.view(lowercase__ ) # reshape back to match original input shape __lowercase = z_q.permute(0 ,3 ,1 ,2 ).contiguous() return z_q class lowercase_ (lowerCamelCase__ ): """simple docstring""" def __init__( self : str ,lowercase__ : Union[str, Any] ,lowercase__ : Union[str, Any]=False ): __lowercase = parameters __lowercase , __lowercase = torch.chunk(lowercase__ ,2 ,dim=1 ) __lowercase = torch.clamp(self.logvar ,-3_0.0 ,2_0.0 ) __lowercase = deterministic __lowercase = torch.exp(0.5 * self.logvar ) __lowercase = torch.exp(self.logvar ) if self.deterministic: __lowercase = __lowercase = torch.zeros_like( self.mean ,device=self.parameters.device ,dtype=self.parameters.dtype ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : Optional[torch.Generator] = None ): # make sure sample is on the same device as the parameters and has same dtype __lowercase = randn_tensor( self.mean.shape ,generator=lowercase__ ,device=self.parameters.device ,dtype=self.parameters.dtype ) __lowercase = self.mean + self.std * sample return x def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Any=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean ,2 ) + self.var - 1.0 - self.logvar ,dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean ,2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar ,dim=[1, 2, 3] ,) def SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : List[str] ,lowercase__ : str=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) __lowercase = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,2 ) / self.var ,dim=lowercase__ ) def SCREAMING_SNAKE_CASE ( self : str ): return self.mean
104
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
0
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class __UpperCamelCase ( unittest.TestCase ): def __a ( self ) -> int: a : Tuple = inspect.getfile(accelerate.test_utils ) a : List[Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["scripts", "external_deps", "test_metrics.py"] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 a : Any = test_metrics @require_cpu def __a ( self ) -> Tuple: debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def __a ( self ) -> List[Any]: debug_launcher(self.test_metrics.main ) @require_single_gpu def __a ( self ) -> Optional[int]: self.test_metrics.main() @require_multi_gpu def __a ( self ) -> Optional[int]: print(f"""Found {torch.cuda.device_count()} devices.""" ) a : Optional[int] = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() )
105
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) __UpperCamelCase : List[str] = { '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''', } class SCREAMING_SNAKE_CASE ( a_ , a_ ): """simple docstring""" lowercase__ = "resnet" lowercase__ = ["basic", "bottleneck"] def __init__( self : str ,lowercase_ : Optional[Any]=3 ,lowercase_ : List[Any]=6_4 ,lowercase_ : Optional[int]=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] ,lowercase_ : str=[3, 4, 6, 3] ,lowercase_ : str="bottleneck" ,lowercase_ : List[Any]="relu" ,lowercase_ : Dict=False ,lowercase_ : List[str]=None ,lowercase_ : Tuple=None ,**lowercase_ : List[str] ,): super().__init__(**lowercase_ ) if layer_type not in self.layer_types: raise ValueError(F'layer_type={layer_type} is not one of {",".join(self.layer_types )}' ) lowerCAmelCase__ : Tuple = num_channels lowerCAmelCase__ : str = embedding_size lowerCAmelCase__ : str = hidden_sizes lowerCAmelCase__ : Dict = depths lowerCAmelCase__ : Optional[Any] = layer_type lowerCAmelCase__ : Optional[int] = hidden_act lowerCAmelCase__ : Union[str, Any] = downsample_in_first_stage lowerCAmelCase__ : str = ['''stem'''] + [F'stage{idx}' for idx in range(1 ,len(lowercase_ ) + 1 )] lowerCAmelCase__ ,lowerCAmelCase__ : List[str] = get_aligned_output_features_output_indices( out_features=lowercase_ ,out_indices=lowercase_ ,stage_names=self.stage_names ) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = version.parse("1.11" ) @property def __lowerCAmelCase ( self : int ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __lowerCAmelCase ( self : Dict ): return 1E-3
106
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
0
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __lowerCAmelCase : Tuple = '▁' __lowerCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class snake_case__ (_UpperCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = BertGenerationTokenizer SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : str = True def __UpperCAmelCase ( self : int ) -> List[Any]: super().setUp() a = BertGenerationTokenizer(__lowerCamelCase , keep_accents=__lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: a = "<s>" a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCamelCase ) , __lowerCamelCase ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(__lowerCamelCase ) , 10_02 ) def __UpperCAmelCase ( self : str ) -> Optional[int]: self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def __UpperCAmelCase ( self : List[str] ) -> int: a = BertGenerationTokenizer(__lowerCamelCase , keep_accents=__lowerCamelCase ) a = tokenizer.tokenize("This is a test" ) self.assertListEqual(__lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [2_85, 46, 10, 1_70, 3_82] , ) a = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __lowerCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) a = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) a = tokenizer.convert_ids_to_tokens(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def __UpperCAmelCase ( self : Dict ) -> int: return BertGenerationTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) @slow def __UpperCAmelCase ( self : List[Any] ) -> int: a = "Hello World!" a = [1_85_36, 22_60, 1_01] self.assertListEqual(__lowerCamelCase , self.big_tokenizer.encode(__lowerCamelCase ) ) @slow def __UpperCAmelCase ( self : Optional[Any] ) -> Any: a = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) a = [ 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, ] self.assertListEqual(__lowerCamelCase , self.big_tokenizer.encode(__lowerCamelCase ) ) @require_torch @slow def __UpperCAmelCase ( self : Dict ) -> Any: import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence a = list(self.big_tokenizer.get_vocab().keys() )[:10] a = " ".join(__lowerCamelCase ) a = self.big_tokenizer.encode_plus(__lowerCamelCase , return_tensors="pt" , return_token_type_ids=__lowerCamelCase ) a = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=__lowerCamelCase ) a = BertGenerationConfig() a = BertGenerationEncoder(__lowerCamelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__lowerCamelCase ) model(**__lowerCamelCase ) @slow def __UpperCAmelCase ( self : Dict ) -> Any: # fmt: off a = {"input_ids": [[3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14], [4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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], [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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowerCamelCase , model_name="google/bert_for_seq_generation_L-24_bbc_encoder" , revision="c817d1fd1be2ffa69431227a1fe320544943d4db" , )
107
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" from collections.abc import Iterable from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''_T''') class SCREAMING_SNAKE_CASE__ ( Generic[_T] ): """simple docstring""" def __init__( self , snake_case__ = None ): """simple docstring""" lowerCAmelCase : list[_T] = list(iterable or [] ) lowerCAmelCase : list[_T] = [] def __len__( self ): """simple docstring""" return len(self._stacka ) + len(self._stacka ) def __repr__( self ): """simple docstring""" return f"""Queue({tuple(self._stacka[::-1] + self._stacka )})""" def lowercase__ ( self , snake_case__ ): """simple docstring""" self._stacka.append(snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[int] = self._stacka.pop lowerCAmelCase : List[str] = self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError("Queue is empty" ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
108
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
0
"""simple docstring""" from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : List[Any] = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(_SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' UpperCAmelCase : Any = self._create_example_records() UpperCAmelCase : int = Dataset.from_list(_SCREAMING_SNAKE_CASE ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(_SCREAMING_SNAKE_CASE ): self.assertDictEqual(_SCREAMING_SNAKE_CASE , example_records[i] ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : List[str] = self._create_example_records() UpperCAmelCase : List[str] = Dataset.from_list(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : List[str] = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: # checks what happens with missing columns '''simple docstring''' UpperCAmelCase : Optional[int] = [{"""col_1""": 1}, {"""col_2""": """x"""}] UpperCAmelCase : List[str] = Dataset.from_list(_SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def SCREAMING_SNAKE_CASE ( self ) -> Tuple: # checks if the type can be inferred from the second record '''simple docstring''' UpperCAmelCase : Union[str, Any] = [{"""col_1""": []}, {"""col_1""": [1, 2]}] UpperCAmelCase : List[Any] = Dataset.from_list(_SCREAMING_SNAKE_CASE ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : Dict = Dataset.from_list([] ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 0 ) self.assertListEqual(dset.column_names , [] )
109
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
"""simple docstring""" from math import log from scipy.constants import Boltzmann, physical_constants __A = 300 # TEMPERATURE (unit = K) def lowercase_ ( _lowerCamelCase: Any , _lowerCamelCase: Dict , _lowerCamelCase: Dict , ) -> float: '''simple docstring''' if donor_conc <= 0: raise ValueError("Donor concentration should be positive" ) elif acceptor_conc <= 0: raise ValueError("Acceptor concentration should be positive" ) elif intrinsic_conc <= 0: raise ValueError("Intrinsic concentration should be positive" ) elif donor_conc <= intrinsic_conc: raise ValueError( "Donor concentration should be greater than intrinsic concentration" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( "Acceptor concentration should be greater than intrinsic concentration" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
135
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
0
import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) class _lowerCamelCase( _a ): def __init__( self, *lowerCamelCase, **lowerCamelCase) -> Any: """simple docstring""" warnings.warn( 'The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DonutImageProcessor instead.', __UpperCAmelCase, ) super().__init__(*__UpperCAmelCase, **__UpperCAmelCase)
21
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
0
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __snake_case ( unittest.TestCase ): """simple docstring""" def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __A : Union[str, Any] = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(__UpperCAmelCase ) def UpperCamelCase__( self ): '''simple docstring''' __A : Dict = 'sshleifer/tiny-gpt2' __A : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : Any = PyTorchBenchmark(__UpperCAmelCase ) __A : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Dict = 'sgugger/tiny-distilbert-classification' __A : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , only_pretrain_model=__UpperCAmelCase , ) __A : Optional[Any] = PyTorchBenchmark(__UpperCAmelCase ) __A : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Any = 'sshleifer/tiny-gpt2' __A : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , torchscript=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) __A : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def UpperCamelCase__( self ): '''simple docstring''' __A : List[Any] = 'sshleifer/tiny-gpt2' __A : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , fpaa=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) __A : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Optional[int] = 'sshleifer/tiny-gpt2' __A : List[Any] = AutoConfig.from_pretrained(__UpperCAmelCase ) # set architectures equal to `None` __A : str = None __A : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : Any = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) __A : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Optional[Any] = 'sshleifer/tiny-gpt2' __A : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) __A : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def UpperCamelCase__( self ): '''simple docstring''' __A : List[str] = 'sshleifer/tiny-gpt2' __A : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=__UpperCAmelCase , multi_process=__UpperCAmelCase , ) __A : Optional[int] = PyTorchBenchmark(__UpperCAmelCase ) __A : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Any = 'sshleifer/tiny-gpt2' __A : Tuple = AutoConfig.from_pretrained(__UpperCAmelCase ) __A : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : List[Any] = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) __A : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Union[str, Any] = 'sshleifer/tinier_bart' __A : Dict = AutoConfig.from_pretrained(__UpperCAmelCase ) __A : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : Tuple = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) __A : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Tuple = 'sshleifer/tiny-gpt2' __A : str = AutoConfig.from_pretrained(__UpperCAmelCase ) __A : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : List[str] = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) __A : Any = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Any = 'sshleifer/tinier_bart' __A : Dict = AutoConfig.from_pretrained(__UpperCAmelCase ) __A : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCAmelCase , ) __A : Optional[Any] = PyTorchBenchmark(__UpperCAmelCase , configs=[config] ) __A : int = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCamelCase__( self ): '''simple docstring''' __A : Union[str, Any] = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: __A : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , save_to_csv=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__UpperCAmelCase , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(__UpperCAmelCase , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(__UpperCAmelCase , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(__UpperCAmelCase , '''train_time.csv''' ) , env_info_csv_file=os.path.join(__UpperCAmelCase , '''env.csv''' ) , multi_process=__UpperCAmelCase , ) __A : List[Any] = PyTorchBenchmark(__UpperCAmelCase ) benchmark.run() self.assertTrue(Path(os.path.join(__UpperCAmelCase , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , '''env.csv''' ) ).exists() ) def UpperCamelCase__( self ): '''simple docstring''' __A : Dict = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(__lowerCamelCase ): self.assertTrue(hasattr(__UpperCAmelCase , '''sequential''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''cumulative''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''current''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCAmelCase , inference=__UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__UpperCAmelCase , '''log.txt''' ) , log_print=__UpperCAmelCase , trace_memory_line_by_line=__UpperCAmelCase , multi_process=__UpperCAmelCase , ) __A : List[Any] = PyTorchBenchmark(__UpperCAmelCase ) __A : Dict = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(__UpperCAmelCase , '''log.txt''' ) ).exists() )
179
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def A_ ( _lowercase = 3 ): '''simple docstring''' if isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): raise TypeError("""number of qubits must be a integer.""" ) if number_of_qubits <= 0: raise ValueError("""number of qubits must be > 0.""" ) if math.floor(_SCREAMING_SNAKE_CASE ) != number_of_qubits: raise ValueError("""number of qubits must be exact integer.""" ) if number_of_qubits > 10: raise ValueError("""number of qubits too large to simulate(>10).""" ) snake_case_ :List[Any] = QuantumRegister(_SCREAMING_SNAKE_CASE, """qr""" ) snake_case_ :Any = ClassicalRegister(_SCREAMING_SNAKE_CASE, """cr""" ) snake_case_ :List[str] = QuantumCircuit(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) snake_case_ :List[str] = number_of_qubits for i in range(_SCREAMING_SNAKE_CASE ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(_SCREAMING_SNAKE_CASE ): quantum_circuit.cp(np.pi / 2 ** (counter - j), _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(_SCREAMING_SNAKE_CASE, number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) # simulate with 10000 shots snake_case_ :Any = Aer.get_backend("""qasm_simulator""" ) snake_case_ :Any = execute(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, shots=10000 ) return job.result().get_counts(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
66
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
0
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" _snake_case = ConsistencyModelPipeline _snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt _snake_case = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) @property def A__ ( self )-> Dict: '''simple docstring''' __UpperCamelCase = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet''' , ) return unet @property def A__ ( self )-> int: '''simple docstring''' __UpperCamelCase = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet_class_cond''' , ) return unet def A__ ( self , SCREAMING_SNAKE_CASE_=False )-> Any: '''simple docstring''' if class_cond: __UpperCamelCase = self.dummy_cond_unet else: __UpperCamelCase = self.dummy_uncond_unet # Default to CM multistep sampler __UpperCamelCase = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __UpperCamelCase = { 'unet': unet, 'scheduler': scheduler, } return components def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 )-> str: '''simple docstring''' if str(__UpperCAmelCase ).startswith('''mps''' ): __UpperCamelCase = torch.manual_seed(__UpperCAmelCase ) else: __UpperCamelCase = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __UpperCamelCase = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def A__ ( self )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.get_dummy_components() __UpperCamelCase = ConsistencyModelPipeline(**__UpperCAmelCase ) __UpperCamelCase = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def A__ ( self )-> List[Any]: '''simple docstring''' __UpperCamelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.get_dummy_components(class_cond=__UpperCAmelCase ) __UpperCamelCase = ConsistencyModelPipeline(**__UpperCAmelCase ) __UpperCamelCase = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCamelCase = 0 __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def A__ ( self )-> Optional[Any]: '''simple docstring''' __UpperCamelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.get_dummy_components() __UpperCamelCase = ConsistencyModelPipeline(**__UpperCAmelCase ) __UpperCamelCase = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCamelCase = 1 __UpperCamelCase = None __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def A__ ( self )-> Optional[int]: '''simple docstring''' __UpperCamelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.get_dummy_components(class_cond=__UpperCAmelCase ) __UpperCamelCase = ConsistencyModelPipeline(**__UpperCAmelCase ) __UpperCamelCase = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCamelCase = 1 __UpperCamelCase = None __UpperCamelCase = 0 __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def A__ ( self )-> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=(1, 3, 64, 64) )-> str: '''simple docstring''' __UpperCamelCase = torch.manual_seed(__UpperCAmelCase ) __UpperCamelCase = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __UpperCamelCase = self.get_fixed_latents(seed=__UpperCAmelCase , device=__UpperCAmelCase , dtype=__UpperCAmelCase , shape=__UpperCAmelCase ) __UpperCamelCase = latents return inputs def A__ ( self , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=(1, 3, 64, 64) )-> Dict: '''simple docstring''' if type(__UpperCAmelCase ) == str: __UpperCamelCase = torch.device(__UpperCAmelCase ) __UpperCamelCase = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __UpperCamelCase = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase , device=__UpperCAmelCase , dtype=__UpperCAmelCase ) return latents def A__ ( self )-> Optional[int]: '''simple docstring''' __UpperCamelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __UpperCamelCase = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __UpperCamelCase = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_inputs() __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def A__ ( self )-> str: '''simple docstring''' __UpperCamelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __UpperCamelCase = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __UpperCamelCase = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_inputs() __UpperCamelCase = 1 __UpperCamelCase = None __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 @require_torch_a def A__ ( self )-> List[Any]: '''simple docstring''' __UpperCamelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __UpperCamelCase = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __UpperCamelCase = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_inputs(get_fixed_latents=__UpperCAmelCase , device=__UpperCAmelCase ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__UpperCAmelCase , enable_math=__UpperCAmelCase , enable_mem_efficient=__UpperCAmelCase ): __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @require_torch_a def A__ ( self )-> int: '''simple docstring''' __UpperCamelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __UpperCamelCase = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __UpperCamelCase = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_inputs(get_fixed_latents=__UpperCAmelCase , device=__UpperCAmelCase ) __UpperCamelCase = 1 __UpperCamelCase = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__UpperCAmelCase , enable_math=__UpperCAmelCase , enable_mem_efficient=__UpperCAmelCase ): __UpperCamelCase = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
328
"""simple docstring""" import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
0
from __future__ import annotations def _lowerCAmelCase (_lowerCAmelCase): if len(_SCREAMING_SNAKE_CASE) < 2: raise ValueError("Monogons and Digons are not polygons in the Euclidean space") if any(i <= 0 for i in nums): raise ValueError("All values must be greater than 0") UpperCamelCase_ = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1]) if __name__ == "__main__": import doctest doctest.testmod()
128
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: List[str] =np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCamelCase__: List[Any] =np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = """sigmoid""" lowercase_ = """softmax""" lowercase_ = """none""" @add_end_docstrings( __SCREAMING_SNAKE_CASE , R"\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `\"sigmoid\"`: Applies the sigmoid function on the output.\n - `\"softmax\"`: Applies the softmax function on the output.\n - `\"none\"`: Does not apply any function on the output.\n " , ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = False lowercase_ = ClassificationFunction.NONE def __init__(self : Optional[Any] , **UpperCAmelCase_ : Tuple) ->Any: '''simple docstring''' super().__init__(**__UpperCAmelCase) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int="" , **UpperCAmelCase_ : Dict) ->int: '''simple docstring''' lowerCamelCase__: Optional[int] =tokenizer_kwargs lowerCamelCase__: List[Any] ={} if hasattr(self.model.config , "return_all_scores") and return_all_scores is None: lowerCamelCase__: List[Any] =self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase) or top_k is None: lowerCamelCase__: int =top_k lowerCamelCase__: Dict =False elif return_all_scores is not None: warnings.warn( "`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of" " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`." , __UpperCAmelCase , ) if return_all_scores: lowerCamelCase__: List[Any] =None else: lowerCamelCase__: Union[str, Any] =1 if isinstance(__UpperCAmelCase , __UpperCAmelCase): lowerCamelCase__: Union[str, Any] =ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCamelCase__: List[Any] =function_to_apply return preprocess_params, {}, postprocess_params def __call__(self : Dict , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =super().__call__(*__UpperCAmelCase , **__UpperCAmelCase) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCamelCase__: Optional[Any] ='top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : int) ->str: '''simple docstring''' lowerCamelCase__: Dict =self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase) elif isinstance(__UpperCAmelCase , __UpperCAmelCase) and len(__UpperCAmelCase) == 1 and isinstance(inputs[0] , __UpperCAmelCase) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase) elif isinstance(__UpperCAmelCase , __UpperCAmelCase): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair.") return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Optional[int]) ->str: '''simple docstring''' return self.model(**__UpperCAmelCase) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : List[Any]=True) ->List[str]: '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCamelCase__: str =ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCamelCase__: int =ClassificationFunction.SOFTMAX elif hasattr(self.model.config , "function_to_apply") and function_to_apply is None: lowerCamelCase__: Optional[Any] =self.model.config.function_to_apply else: lowerCamelCase__: Dict =ClassificationFunction.NONE lowerCamelCase__: int =model_outputs['logits'][0] lowerCamelCase__: Union[str, Any] =outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCamelCase__: Dict =sigmoid(__UpperCAmelCase) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCamelCase__: int =softmax(__UpperCAmelCase) elif function_to_apply == ClassificationFunction.NONE: lowerCamelCase__: Tuple =outputs else: raise ValueError(F"""Unrecognized `function_to_apply` argument: {function_to_apply}""") if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCamelCase__: Any =[ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase) ] if not _legacy: dict_scores.sort(key=lambda UpperCAmelCase_: x["score"] , reverse=__UpperCAmelCase) if top_k is not None: lowerCamelCase__: List[str] =dict_scores[:top_k] return dict_scores
10
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
0
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[str] ): '''simple docstring''' lowerCAmelCase = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F'Building PyTorch model from configuration: {config}' ) lowerCAmelCase = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--bert_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
46
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" lowerCamelCase__ : Optional[int] = '''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
246
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
0
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 UpperCAmelCase : '''simple docstring''' def __init__( self : Any , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple=1_3 , lowerCAmelCase_ : Union[str, Any]=7 , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : int=9_9 , lowerCAmelCase_ : Tuple=3_2 , lowerCAmelCase_ : List[Any]=5 , lowerCAmelCase_ : Optional[Any]=4 , lowerCAmelCase_ : List[Any]=3_7 , lowerCAmelCase_ : Optional[int]="gelu" , lowerCAmelCase_ : List[Any]=0.1 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : Any=5_0 , lowerCAmelCase_ : Optional[int]=0.02 , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : int=None , ): """simple docstring""" _A: Tuple = parent _A: List[str] = batch_size _A: List[Any] = seq_length _A: str = is_training _A: Dict = use_input_mask _A: Union[str, Any] = vocab_size _A: Union[str, Any] = hidden_size _A: Optional[Any] = num_hidden_layers _A: List[str] = num_attention_heads _A: Optional[Any] = intermediate_size _A: Union[str, Any] = hidden_act _A: int = hidden_dropout_prob _A: int = attention_probs_dropout_prob _A: Union[str, Any] = max_position_embeddings _A: Union[str, Any] = initializer_range _A: List[Any] = use_labels _A: List[Any] = scope def __magic_name__ ( self : str ): """simple docstring""" _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: Tuple = None if self.use_input_mask: _A: Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: _A: int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: Optional[int] = self.get_config() return config, input_ids, input_mask, token_labels def __magic_name__ ( self : Optional[Any] ): """simple docstring""" 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=__UpperCAmelCase , initializer_range=self.initializer_range , ) def __magic_name__ ( self : Any ): """simple docstring""" ( _A ): Optional[Any] = self.prepare_config_and_inputs() _A: Dict = 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 __magic_name__ ( self : int , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" _A: Tuple = BertGenerationEncoder(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() _A: str = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase ) _A: int = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" _A: str = True _A: List[str] = BertGenerationEncoder(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() _A: List[str] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , ) _A: str = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" _A: Tuple = True _A: Union[str, Any] = True _A: Optional[int] = BertGenerationDecoder(config=__UpperCAmelCase ).to(__UpperCAmelCase ).eval() # first forward pass _A: int = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase , ) _A: Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _A: Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) _A: Any = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _A: Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) _A: List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) _A: Optional[int] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )['hidden_states'][0] _A: int = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )['hidden_states'][0] # select random slice _A: Tuple = 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(__UpperCAmelCase , __UpperCAmelCase , atol=1e-3 ) ) def __magic_name__ ( self : int , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str , *lowerCAmelCase_ : List[str] , ): """simple docstring""" _A: int = BertGenerationDecoder(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() _A: Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : str ): """simple docstring""" _A: Any = self.prepare_config_and_inputs() _A: Union[str, Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Any = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __UpperCamelCase : Optional[Any] = (BertGenerationDecoder,) if is_torch_available() else () __UpperCamelCase : Optional[Any] = ( {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder} if is_torch_available() else {} ) def __magic_name__ ( self : str ): """simple docstring""" _A: int = BertGenerationEncoderTester(self ) _A: int = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=3_7 ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : List[str] ): """simple docstring""" _A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: List[str] = self.model_tester.prepare_config_and_inputs() _A: List[str] = 'bert' self.model_tester.create_and_check_model(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: List[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__UpperCAmelCase ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__UpperCAmelCase ) def __magic_name__ ( self : str ): """simple docstring""" ( _A ): int = self.model_tester.prepare_config_and_inputs_for_decoder() _A: int = None self.model_tester.create_and_check_model_as_decoder( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) def __magic_name__ ( self : int ): """simple docstring""" _A: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*__UpperCAmelCase ) @slow def __magic_name__ ( self : int ): """simple docstring""" _A: Dict = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) self.assertIsNotNone(__UpperCAmelCase ) @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: str = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) _A: Tuple = torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]] ) with torch.no_grad(): _A: Dict = model(__UpperCAmelCase )[0] _A: Any = torch.Size([1, 8, 1_0_2_4] ) self.assertEqual(output.shape , __UpperCAmelCase ) _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] , __UpperCAmelCase , atol=1e-4 ) ) @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Union[str, Any] = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) _A: str = torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]] ) with torch.no_grad(): _A: Any = model(__UpperCAmelCase )[0] _A: Tuple = torch.Size([1, 8, 5_0_3_5_8] ) self.assertEqual(output.shape , __UpperCAmelCase ) _A: Tuple = 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] , __UpperCAmelCase , atol=1e-4 ) )
121
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class __lowerCAmelCase : UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None # sigma(t_i) @classmethod def lowerCamelCase__ ( cls :str ): '''simple docstring''' return cls() @dataclass class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 class __lowerCAmelCase ( __magic_name__ , __magic_name__ ): @property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return True @register_to_config def __init__( self :List[Any] , __magic_name__ :Optional[Any] = 0.02 , __magic_name__ :List[Any] = 100 , __magic_name__ :List[Any] = 1.007 , __magic_name__ :str = 80 , __magic_name__ :int = 0.05 , __magic_name__ :Optional[int] = 50 , ): '''simple docstring''' pass def lowerCamelCase__ ( self :int ): '''simple docstring''' return KarrasVeSchedulerState.create() def lowerCamelCase__ ( self :List[str] , __magic_name__ :Dict , __magic_name__ :Optional[Any] , __magic_name__ :List[str] = () ): '''simple docstring''' a = jnp.arange(0 , __UpperCAmelCase )[::-1].copy() a = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=__UpperCAmelCase , schedule=jnp.array(__UpperCAmelCase , dtype=jnp.floataa ) , timesteps=__UpperCAmelCase , ) def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :Optional[Any] , __magic_name__ :Any , __magic_name__ :int , __magic_name__ :Union[str, Any] , ): '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: a = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: a = 0 # sample eps ~ N(0, S_noise^2 * I) a = random.split(__UpperCAmelCase , num=1 ) a = self.config.s_noise * random.normal(key=__UpperCAmelCase , shape=sample.shape ) a = sigma + gamma * sigma a = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def lowerCamelCase__ ( self :str , __magic_name__ :Tuple , __magic_name__ :Union[str, Any] , __magic_name__ :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Optional[int] , __magic_name__ :Union[str, Any] = True , ): '''simple docstring''' a = sample_hat + sigma_hat * model_output a = (sample_hat - pred_original_sample) / sigma_hat a = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__UpperCAmelCase , derivative=__UpperCAmelCase , state=__UpperCAmelCase ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Dict , __magic_name__ :int , __magic_name__ :str , __magic_name__ :Optional[Any] , __magic_name__ :Union[str, Any] , __magic_name__ :int , __magic_name__ :List[str] , __magic_name__ :Optional[int] = True , ): '''simple docstring''' a = sample_prev + sigma_prev * model_output a = (sample_prev - pred_original_sample) / sigma_prev a = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__UpperCAmelCase , derivative=__UpperCAmelCase , state=__UpperCAmelCase ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :Dict , __magic_name__ :int , __magic_name__ :Any , __magic_name__ :Dict ): '''simple docstring''' raise NotImplementedError()
228
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( a__ , a__ , unittest.TestCase ): snake_case__ = StableDiffusionXLImgaImgPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} snake_case__ = PipelineTesterMixin.required_optional_params - {"""latents"""} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case__ = IMAGE_TO_IMAGE_IMAGE_PARAMS snake_case__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase__ ( self : Dict ): torch.manual_seed(0 ) __lowerCamelCase : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type="text_time" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) __lowerCamelCase : str = EulerDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule="scaled_linear" , timestep_spacing="leading" , ) torch.manual_seed(0 ) __lowerCamelCase : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __lowerCamelCase : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=32 , ) __lowerCamelCase : int = CLIPTextModel(__UpperCAmelCase ) __lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=__UpperCAmelCase ) __lowerCamelCase : Any = CLIPTextModelWithProjection(__UpperCAmelCase ) __lowerCamelCase : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=__UpperCAmelCase ) __lowerCamelCase : str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : Dict , UpperCAmelCase : Dict=0 ): __lowerCamelCase : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) __lowerCamelCase : Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith("mps" ): __lowerCamelCase : Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: __lowerCamelCase : Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __lowerCamelCase : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.7_5, } return inputs def lowerCamelCase__ ( self : Tuple ): __lowerCamelCase : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : int = self.get_dummy_components() __lowerCamelCase : List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) __lowerCamelCase : str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __lowerCamelCase : str = self.get_dummy_inputs(__UpperCAmelCase ) __lowerCamelCase : int = sd_pipe(**__UpperCAmelCase ).images __lowerCamelCase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase : List[str] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : Optional[Any] ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self : Any ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self : Any ): pass def lowerCamelCase__ ( self : Optional[Any] ): __lowerCamelCase : Tuple = self.get_dummy_components() __lowerCamelCase : str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) __lowerCamelCase : str = sd_pipe.to(__UpperCAmelCase ) __lowerCamelCase : List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds __lowerCamelCase : int = self.get_dummy_inputs(__UpperCAmelCase ) __lowerCamelCase : Optional[int] = 3 * ['this is a negative prompt'] __lowerCamelCase : Tuple = negative_prompt __lowerCamelCase : str = 3 * [inputs['prompt']] __lowerCamelCase : Optional[Any] = sd_pipe(**__UpperCAmelCase ) __lowerCamelCase : List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds __lowerCamelCase : Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) __lowerCamelCase : Tuple = 3 * ['this is a negative prompt'] __lowerCamelCase : str = 3 * [inputs.pop("prompt" )] ( __lowerCamelCase ) : List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) __lowerCamelCase : str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) __lowerCamelCase : Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCamelCase__ ( self : List[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : List[Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : str="cpu" , UpperCAmelCase : str=torch.floataa , UpperCAmelCase : List[Any]=0 ): __lowerCamelCase : Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __lowerCamelCase : Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 64, 64) ) __lowerCamelCase : Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) __lowerCamelCase : int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def lowerCamelCase__ ( self : List[str] ): __lowerCamelCase : List[Any] = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base" ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __lowerCamelCase : Tuple = self.get_inputs(__UpperCAmelCase ) __lowerCamelCase : int = pipe(**__UpperCAmelCase ).images __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __lowerCamelCase : List[str] = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
135
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
SCREAMING_SNAKE_CASE : int = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def UpperCamelCase_( lowerCamelCase_ ) -> str: assert type(_SCREAMING_SNAKE_CASE ) in (int, float) and decimal == int(_SCREAMING_SNAKE_CASE ) _lowercase : Optional[int] = int(_SCREAMING_SNAKE_CASE ) _lowercase : List[Any] = '' _lowercase : str = False if decimal < 0: _lowercase : Optional[Any] = True decimal *= -1 while decimal > 0: _lowercase : Union[str, Any] = divmod(_SCREAMING_SNAKE_CASE , 16 ) _lowercase : Union[str, Any] = values[remainder] + hexadecimal _lowercase : List[Any] = '0x' + hexadecimal if negative: _lowercase : List[Any] = '-' + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
21
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
"""simple docstring""" import numpy as np from transformers import Pipeline def __lowercase ( snake_case_ : Union[str, Any] ) ->Any: '''simple docstring''' __A : Any = np.max(_SCREAMING_SNAKE_CASE ,axis=-1 ,keepdims=_SCREAMING_SNAKE_CASE ) __A : Any = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 ,keepdims=_SCREAMING_SNAKE_CASE ) class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def UpperCamelCase__( self , **__lowerCamelCase ): '''simple docstring''' __A : List[Any] = {} if "second_text" in kwargs: __A : List[Any] = kwargs['second_text'] return preprocess_kwargs, {}, {} def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase=None ): '''simple docstring''' return self.tokenizer(__UpperCAmelCase , text_pair=__UpperCAmelCase , return_tensors=self.framework ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' __A : Any = model_outputs.logits[0].numpy() __A : Dict = softmax(__UpperCAmelCase ) __A : str = np.argmax(__UpperCAmelCase ) __A : int = self.model.config.idalabel[best_class] __A : Tuple = probabilities[best_class].item() __A : int = logits.tolist() return {"label": label, "score": score, "logits": logits}
179
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = pipeline( 'document-question-answering' , model='naver-clova-ix/donut-base-finetuned-docvqa' , tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa' ) , feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
0
"""simple docstring""" import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin __a = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right __a = 25_00_04 __a = 25_00_20 @require_sentencepiece @require_tokenizers class lowerCamelCase ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : Optional[int] = MBartaaTokenizer _A : List[Any] = MBartaaTokenizerFast _A : str = True _A : int = True def lowerCAmelCase_ ( self: Dict ) -> List[str]: super().setUp() # We have a SentencePiece fixture for testing snake_case_ :str = MBartaaTokenizer(__UpperCAmelCase , src_lang="""en_XX""" , tgt_lang="""ro_RO""" , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase_ ( self: Any ) -> Union[str, Any]: snake_case_ :Tuple = '<s>' snake_case_ :Optional[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def lowerCAmelCase_ ( self: Optional[Any] ) -> Tuple: snake_case_ :int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(__UpperCAmelCase ) , 1_054 ) def lowerCAmelCase_ ( self: Tuple ) -> List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 1_054 ) def lowerCAmelCase_ ( self: Any ) -> Optional[int]: snake_case_ :Tuple = MBartaaTokenizer(__UpperCAmelCase , src_lang="""en_XX""" , tgt_lang="""ro_RO""" , keep_accents=__UpperCAmelCase ) snake_case_ :Any = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__UpperCAmelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) snake_case_ :List[str] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __UpperCAmelCase , [SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """."""] , ) snake_case_ :List[Any] = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) snake_case_ :str = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """."""] , ) @slow def lowerCAmelCase_ ( self: Optional[Any] ) -> Dict: snake_case_ :Any = {'input_ids': [[250_004, 11_062, 82_772, 7, 15, 82_772, 538, 51_529, 237, 17_198, 1_290, 206, 9, 215_175, 1_314, 136, 17_198, 1_290, 206, 9, 56_359, 42, 122_009, 9, 16_466, 16, 87_344, 4_537, 9, 4_717, 78_381, 6, 159_958, 7, 15, 24_480, 618, 4, 527, 22_693, 5_428, 4, 2_777, 24_480, 9_874, 4, 43_523, 594, 4, 803, 18_392, 33_189, 18, 4, 43_523, 24_447, 12_399, 100, 24_955, 83_658, 9_626, 144_057, 15, 839, 22_335, 16, 136, 24_955, 83_658, 83_479, 15, 39_102, 724, 16, 678, 645, 2_789, 1_328, 4_589, 42, 122_009, 115_774, 23, 805, 1_328, 46_876, 7, 136, 53_894, 1_940, 42_227, 41_159, 17_721, 823, 425, 4, 27_512, 98_722, 206, 136, 5_531, 4_970, 919, 17_336, 5, 2], [250_004, 20_080, 618, 83, 82_775, 47, 479, 9, 1_517, 73, 53_894, 333, 80_581, 110_117, 18_811, 5_256, 1_295, 51, 152_526, 297, 7_986, 390, 124_416, 538, 35_431, 214, 98, 15_044, 25_737, 136, 7_108, 43_701, 23, 756, 135_355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [250_004, 581, 63_773, 119_455, 6, 147_797, 88_203, 7, 645, 70, 21, 3_285, 10_269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name="""facebook/mbart-large-50""" , revision="""d3913889c59cd5c9e456b269c376325eabad57e2""" , ) def lowerCAmelCase_ ( self: List[str] ) -> Dict: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return snake_case_ :Optional[Any] = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart50', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case_ :Union[str, Any] = self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) snake_case_ :Optional[Any] = self.tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) snake_case_ :List[str] = tempfile.mkdtemp() snake_case_ :int = tokenizer_r.save_pretrained(__UpperCAmelCase ) snake_case_ :List[Any] = tokenizer_p.save_pretrained(__UpperCAmelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) snake_case_ :List[Any] = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__UpperCAmelCase , __UpperCAmelCase ) # Checks everything loads correctly in the same way snake_case_ :Any = tokenizer_r.from_pretrained(__UpperCAmelCase ) snake_case_ :Optional[Any] = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__UpperCAmelCase ) # Save tokenizer rust, legacy_format=True snake_case_ :Any = tempfile.mkdtemp() snake_case_ :str = tokenizer_r.save_pretrained(__UpperCAmelCase , legacy_format=__UpperCAmelCase ) snake_case_ :List[Any] = tokenizer_p.save_pretrained(__UpperCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(__UpperCAmelCase , __UpperCAmelCase ) # Checks everything loads correctly in the same way snake_case_ :int = tokenizer_r.from_pretrained(__UpperCAmelCase ) snake_case_ :int = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) shutil.rmtree(__UpperCAmelCase ) # Save tokenizer rust, legacy_format=False snake_case_ :str = tempfile.mkdtemp() snake_case_ :str = tokenizer_r.save_pretrained(__UpperCAmelCase , legacy_format=__UpperCAmelCase ) snake_case_ :List[str] = tokenizer_p.save_pretrained(__UpperCAmelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way snake_case_ :Optional[int] = tokenizer_r.from_pretrained(__UpperCAmelCase ) snake_case_ :Optional[int] = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) shutil.rmtree(__UpperCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' _A : List[str] = """facebook/mbart-large-50-one-to-many-mmt""" _A : Dict = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] _A : str = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei""" """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor""" """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] _A : Union[str, Any] = [EN_CODE, 8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2] @classmethod def lowerCAmelCase_ ( cls: List[Any] ) -> Optional[Any]: snake_case_ :MBartaaTokenizer = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) snake_case_ :List[Any] = 1 return cls def lowerCAmelCase_ ( self: Tuple ) -> List[Any]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 250_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 250_004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 250_020 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""mr_IN"""] , 250_038 ) def lowerCAmelCase_ ( self: List[str] ) -> Optional[Any]: snake_case_ :Optional[int] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __UpperCAmelCase ) def lowerCAmelCase_ ( self: List[Any] ) -> Union[str, Any]: self.assertIn(__UpperCAmelCase , self.tokenizer.all_special_ids ) snake_case_ :Dict = [RO_CODE, 884, 9_019, 96, 9, 916, 86_792, 36, 18_743, 15_596, 5, 2] snake_case_ :str = self.tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) snake_case_ :Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , __UpperCAmelCase ) def lowerCAmelCase_ ( self: int ) -> List[str]: snake_case_ :str = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , __UpperCAmelCase ) snake_case_ :Dict = 10 snake_case_ :List[str] = self.tokenizer(__UpperCAmelCase , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase ).input_ids[0] self.assertEqual(ids[0] , __UpperCAmelCase ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) def lowerCAmelCase_ ( self: Union[str, Any] ) -> Any: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [250_053, 250_001] ) def lowerCAmelCase_ ( self: Dict ) -> Tuple: snake_case_ :Optional[int] = tempfile.mkdtemp() snake_case_ :List[str] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__UpperCAmelCase ) snake_case_ :Optional[int] = MBartaaTokenizer.from_pretrained(__UpperCAmelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __UpperCAmelCase ) @require_torch def lowerCAmelCase_ ( self: str ) -> Tuple: snake_case_ :List[str] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__UpperCAmelCase , return_tensors="""pt""" ) snake_case_ :Dict = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def lowerCAmelCase_ ( self: Dict ) -> List[str]: snake_case_ :Any = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) snake_case_ :List[Any] = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) snake_case_ :Dict = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __UpperCAmelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def lowerCAmelCase_ ( self: List[Any] ) -> Union[str, Any]: snake_case_ :Any = self.tokenizer(self.src_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=3 , return_tensors="""pt""" ) snake_case_ :Optional[Any] = self.tokenizer( text_target=self.tgt_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=10 , return_tensors="""pt""" ) snake_case_ :str = targets['input_ids'] snake_case_ :Union[str, Any] = shift_tokens_right(__UpperCAmelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def lowerCAmelCase_ ( self: str ) -> Optional[int]: snake_case_ :Dict = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { # en_XX, A, test, EOS """input_ids""": [[250_004, 62, 3_034, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 250_001, } , )
66
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
0
import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" _snake_case = """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline""" def A__ ( self , SCREAMING_SNAKE_CASE_=0 )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = np.random.RandomState(__UpperCAmelCase ) __UpperCamelCase = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def A__ ( self )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = pipe(**__UpperCAmelCase ).images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCamelCase = np.array([0.6_5_0_7_2, 0.5_8_4_9_2, 0.4_8_2_1_9, 0.5_5_5_2_1, 0.5_3_1_8_0, 0.5_5_9_3_9, 0.5_0_6_9_7, 0.3_9_8_0_0, 0.4_6_4_5_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A__ ( self )-> str: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) __UpperCamelCase = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = pipe(**__UpperCAmelCase ).images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCamelCase = np.array([0.6_5_8_6_3, 0.5_9_4_2_5, 0.4_9_3_2_6, 0.5_6_3_1_3, 0.5_3_8_7_5, 0.5_6_6_2_7, 0.5_1_0_6_5, 0.3_9_7_7_7, 0.4_6_3_3_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A__ ( self )-> str: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) __UpperCamelCase = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = pipe(**__UpperCAmelCase ).images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCamelCase = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A__ ( self )-> List[Any]: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) __UpperCamelCase = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = pipe(**__UpperCAmelCase ).images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCamelCase = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A__ ( self )-> Optional[int]: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) __UpperCamelCase = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = pipe(**__UpperCAmelCase ).images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCamelCase = np.array([0.5_3_8_1_7, 0.6_0_8_1_2, 0.4_7_3_8_4, 0.4_9_5_3_0, 0.5_1_8_9_4, 0.4_9_8_1_4, 0.4_7_9_8_4, 0.3_8_9_5_8, 0.4_4_2_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A__ ( self )-> Dict: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) __UpperCamelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = pipe(**__UpperCAmelCase ).images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCamelCase = np.array([0.5_3_8_9_5, 0.6_0_8_0_8, 0.4_7_9_3_3, 0.4_9_6_0_8, 0.5_1_8_8_6, 0.4_9_9_5_0, 0.4_8_0_5_3, 0.3_8_9_5_7, 0.4_4_2_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A__ ( self )-> Any: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = 3 * [inputs['prompt']] # forward __UpperCamelCase = pipe(**__UpperCAmelCase ) __UpperCamelCase = output.images[0, -3:, -3:, -1] __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = 3 * [inputs.pop('''prompt''' )] __UpperCamelCase = pipe.tokenizer( __UpperCAmelCase , padding='''max_length''' , max_length=pipe.tokenizer.model_max_length , truncation=__UpperCAmelCase , return_tensors='''np''' , ) __UpperCamelCase = text_inputs['input_ids'] __UpperCamelCase = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] __UpperCamelCase = prompt_embeds # forward __UpperCamelCase = pipe(**__UpperCAmelCase ) __UpperCamelCase = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 def A__ ( self )-> Optional[Any]: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = 3 * ['this is a negative prompt'] __UpperCamelCase = negative_prompt __UpperCamelCase = 3 * [inputs['prompt']] # forward __UpperCamelCase = pipe(**__UpperCAmelCase ) __UpperCamelCase = output.images[0, -3:, -3:, -1] __UpperCamelCase = self.get_dummy_inputs() __UpperCamelCase = 3 * [inputs.pop('''prompt''' )] __UpperCamelCase = [] for p in [prompt, negative_prompt]: __UpperCamelCase = pipe.tokenizer( __UpperCAmelCase , padding='''max_length''' , max_length=pipe.tokenizer.model_max_length , truncation=__UpperCAmelCase , return_tensors='''np''' , ) __UpperCamelCase = text_inputs['input_ids'] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) __UpperCamelCase = embeds # forward __UpperCamelCase = pipe(**__UpperCAmelCase ) __UpperCamelCase = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" @property def A__ ( self )-> Tuple: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def A__ ( self )-> List[str]: '''simple docstring''' __UpperCamelCase = ort.SessionOptions() __UpperCamelCase = False return options def A__ ( self )-> Optional[int]: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''onnx''' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = 'A painting of a squirrel eating a burger' np.random.seed(0 ) __UpperCamelCase = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type='''np''' ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCamelCase = np.array([0.0_4_5_2, 0.0_3_9_0, 0.0_0_8_7, 0.0_3_5_0, 0.0_6_1_7, 0.0_3_6_4, 0.0_5_4_4, 0.0_5_2_3, 0.0_7_2_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def A__ ( self )-> Dict: '''simple docstring''' __UpperCamelCase = DDIMScheduler.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , subfolder='''scheduler''' , revision='''onnx''' ) __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = 'open neural network exchange' __UpperCamelCase = np.random.RandomState(0 ) __UpperCamelCase = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=__UpperCAmelCase , output_type='''np''' ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCamelCase = np.array([0.2_8_6_7, 0.1_9_7_4, 0.1_4_8_1, 0.7_2_9_4, 0.7_2_5_1, 0.6_6_6_7, 0.4_1_9_4, 0.5_6_4_2, 0.6_4_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def A__ ( self )-> int: '''simple docstring''' __UpperCamelCase = LMSDiscreteScheduler.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , subfolder='''scheduler''' , revision='''onnx''' ) __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = 'open neural network exchange' __UpperCamelCase = np.random.RandomState(0 ) __UpperCamelCase = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=__UpperCAmelCase , output_type='''np''' ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCamelCase = np.array([0.2_3_0_6, 0.1_9_5_9, 0.1_5_9_3, 0.6_5_4_9, 0.6_3_9_4, 0.5_4_0_8, 0.5_0_6_5, 0.6_0_1_0, 0.6_1_6_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def A__ ( self )-> str: '''simple docstring''' __UpperCamelCase = 0 def test_callback_fn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: __UpperCamelCase = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) __UpperCamelCase = latents[0, -3:, -3:, -1] __UpperCamelCase = np.array( [-0.6_7_7_2, -0.3_8_3_5, -1.2_4_5_6, 0.1_9_0_5, -1.0_9_7_4, 0.6_9_6_7, -1.9_3_5_3, 0.0_1_7_8, 1.0_1_6_7] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) __UpperCamelCase = latents[0, -3:, -3:, -1] __UpperCamelCase = np.array( [-0.3_3_5_1, 0.2_2_4_1, -0.1_8_3_7, -0.2_3_2_5, -0.6_5_7_7, 0.3_3_9_3, -0.0_2_4_1, 0.5_8_9_9, 1.3_8_7_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3 __UpperCamelCase = False __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCamelCase = 'Andromeda galaxy in a bottle' __UpperCamelCase = np.random.RandomState(0 ) pipe( prompt=__UpperCAmelCase , num_inference_steps=5 , guidance_scale=7.5 , generator=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def A__ ( self )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert pipe.safety_checker is None __UpperCamelCase = 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 ) __UpperCamelCase = OnnxStableDiffusionPipeline.from_pretrained(__UpperCAmelCase ) # sanity check that the pipeline still works assert pipe.safety_checker is None __UpperCamelCase = pipe('''example prompt''' , num_inference_steps=2 ).images[0] assert image is not None
328
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
0
import os import sys import unittest UpperCAmelCase : Any =os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path UpperCAmelCase : Any =os.path.join(git_repo_path, """src""", """diffusers""") class _lowercase (unittest.TestCase ): '''simple docstring''' def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = find_backend(" if not is_torch_available():" ) self.assertEqual(__UpperCAmelCase , "torch" ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") UpperCamelCase_ = find_backend(" if not (is_torch_available() and is_transformers_available()):" ) self.assertEqual(__UpperCAmelCase , "torch_and_transformers" ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") UpperCamelCase_ = find_backend( " if not (is_torch_available() and is_transformers_available() and is_onnx_available()):" ) self.assertEqual(__UpperCAmelCase , "torch_and_transformers_and_onnx" ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn("torch" , __UpperCAmelCase ) self.assertIn("torch_and_transformers" , __UpperCAmelCase ) self.assertIn("flax_and_transformers" , __UpperCAmelCase ) self.assertIn("torch_and_transformers_and_onnx" , __UpperCAmelCase ) # Likewise, we can't assert on the exact content of a key self.assertIn("UNet2DModel" , objects["torch"] ) self.assertIn("FlaxUNet2DConditionModel" , objects["flax"] ) self.assertIn("StableDiffusionPipeline" , objects["torch_and_transformers"] ) self.assertIn("FlaxStableDiffusionPipeline" , objects["flax_and_transformers"] ) self.assertIn("LMSDiscreteScheduler" , objects["torch_and_scipy"] ) self.assertIn("OnnxStableDiffusionPipeline" , objects["torch_and_transformers_and_onnx"] ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = create_dummy_object("CONSTANT" , "\'torch\'" ) self.assertEqual(__UpperCAmelCase , "\nCONSTANT = None\n" ) UpperCamelCase_ = create_dummy_object("function" , "\'torch\'" ) self.assertEqual( __UpperCAmelCase , "\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n" ) UpperCamelCase_ = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n' UpperCamelCase_ = create_dummy_object("FakeClass" , "\'torch\'" ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n' UpperCamelCase_ = create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]} ) self.assertEqual(dummy_files["torch"] , __UpperCAmelCase )
128
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
0
def lowerCAmelCase_ ( __a , __a ) -> float: """simple docstring""" if discount_rate < 0: raise ValueError("Discount rate cannot be negative" ) if not cash_flows: raise ValueError("Cash flows list cannot be empty" ) lowerCamelCase__: Union[str, Any] =sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
10
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" import argparse import os import re SCREAMING_SNAKE_CASE__ = "src/transformers/models/auto" # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict SCREAMING_SNAKE_CASE__ = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict") # re pattern that matches identifiers in mappings SCREAMING_SNAKE_CASE__ = re.compile(r"\s*\(\s*\"(\S[^\"]+)\"") def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : List[Any] = False ): '''simple docstring''' with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" ) as f: lowerCAmelCase = f.read() lowerCAmelCase = content.split("""\n""" ) lowerCAmelCase = [] lowerCAmelCase = 0 while line_idx < len(_SCREAMING_SNAKE_CASE ): if _re_intro_mapping.search(lines[line_idx] ) is not None: lowerCAmelCase = len(re.search(R"""^(\s*)\S""" , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(""" """ * indent + """(""" ): new_lines.append(lines[line_idx] ) line_idx += 1 lowerCAmelCase = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": lowerCAmelCase = line_idx while not lines[line_idx].startswith(""" """ * indent + """)""" ): line_idx += 1 blocks.append("""\n""".join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers lowerCAmelCase = sorted(_SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE : _re_identifier.search(_SCREAMING_SNAKE_CASE ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) elif "\n".join(_SCREAMING_SNAKE_CASE ) != content: return True def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : str = False ): '''simple docstring''' lowerCAmelCase = [os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for f in os.listdir(_SCREAMING_SNAKE_CASE ) if f.endswith(""".py""" )] lowerCAmelCase = [sort_auto_mapping(_SCREAMING_SNAKE_CASE , overwrite=_SCREAMING_SNAKE_CASE ) for fname in fnames] if not overwrite and any(_SCREAMING_SNAKE_CASE ): lowerCAmelCase = [f for f, d in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if d] raise ValueError( F'The following files have auto mappings that need sorting: {", ".join(_SCREAMING_SNAKE_CASE )}. Run `make style` to fix' """ this.""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") SCREAMING_SNAKE_CASE__ = parser.parse_args() sort_all_auto_mappings(not args.check_only)
46
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
0
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowerCamelCase__ : Any = NewType('''DataClass''', Any) lowerCamelCase__ : List[str] = NewType('''DataClassType''', Any) def UpperCamelCase ( _lowerCAmelCase : Dict ) -> Dict: if isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( f'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def UpperCamelCase ( _lowerCAmelCase : Optional[int] ) -> Callable[[str], Any]: _UpperCAmelCase : str = {str(_SCREAMING_SNAKE_CASE ): choice for choice in choices} return lambda _lowerCAmelCase : str_to_choice.get(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) def UpperCamelCase ( *, _lowerCAmelCase : List[str] = None, _lowerCAmelCase : List[Any] = None, _lowerCAmelCase : Dict = dataclasses.MISSING, _lowerCAmelCase : Union[str, Any] = dataclasses.MISSING, _lowerCAmelCase : Union[str, Any] = None, **_lowerCAmelCase : Union[str, Any], ) -> dataclasses.Field: if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls _UpperCAmelCase : List[Any] = {} if aliases is not None: _UpperCAmelCase : Optional[Any] = aliases if help is not None: _UpperCAmelCase : int = help return dataclasses.field(metadata=_SCREAMING_SNAKE_CASE, default=_SCREAMING_SNAKE_CASE, default_factory=_SCREAMING_SNAKE_CASE, **_SCREAMING_SNAKE_CASE ) class _UpperCAmelCase ( __a): __a : Iterable[DataClassType] def __init__( self , _A , **_A ) -> str: '''simple docstring''' if "formatter_class" not in kwargs: _UpperCAmelCase : Tuple = ArgumentDefaultsHelpFormatter super().__init__(**__UpperCAmelCase ) if dataclasses.is_dataclass(__UpperCAmelCase ): _UpperCAmelCase : Optional[int] = [dataclass_types] _UpperCAmelCase : List[str] = list(__UpperCAmelCase ) for dtype in self.dataclass_types: self._add_dataclass_arguments(__UpperCAmelCase ) @staticmethod def __snake_case ( _A , _A ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase : Union[str, Any] = f'''--{field.name}''' _UpperCAmelCase : Dict = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , __UpperCAmelCase ): raise RuntimeError( """Unresolved type detected, which should have been done with the help of """ """`typing.get_type_hints` method by default""" ) _UpperCAmelCase : int = kwargs.pop("""aliases""" , [] ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ): _UpperCAmelCase : int = [aliases] _UpperCAmelCase : Optional[Any] = getattr(field.type , """__origin__""" , field.type ) if origin_type is Union or (hasattr(__UpperCAmelCase , """UnionType""" ) and isinstance(__UpperCAmelCase , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(__UpperCAmelCase ) not in field.type.__args__ ): raise ValueError( """Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because""" """ the argument parser only supports one type per argument.""" f''' Problem encountered in field \'{field.name}\'.''' ) if type(__UpperCAmelCase ) not in field.type.__args__: # filter `str` in Union _UpperCAmelCase : Optional[Any] = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] _UpperCAmelCase : Tuple = getattr(field.type , """__origin__""" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) _UpperCAmelCase : Optional[int] = ( field.type.__args__[0] if isinstance(__UpperCAmelCase , field.type.__args__[1] ) else field.type.__args__[1] ) _UpperCAmelCase : Any = getattr(field.type , """__origin__""" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) _UpperCAmelCase : Dict = {} if origin_type is Literal or (isinstance(field.type , __UpperCAmelCase ) and issubclass(field.type , __UpperCAmelCase )): if origin_type is Literal: _UpperCAmelCase : Dict = field.type.__args__ else: _UpperCAmelCase : Dict = [x.value for x in field.type] _UpperCAmelCase : Any = make_choice_type_function(kwargs["""choices"""] ) if field.default is not dataclasses.MISSING: _UpperCAmelCase : int = field.default else: _UpperCAmelCase : Any = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument _UpperCAmelCase : Optional[int] = copy(__UpperCAmelCase ) # Hack because type=bool in argparse does not behave as we want. _UpperCAmelCase : Dict = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. _UpperCAmelCase : Union[str, Any] = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way _UpperCAmelCase : Any = default # This tells argparse we accept 0 or 1 value after --field_name _UpperCAmelCase : Any = '?' # This is the value that will get picked if we do --field_name (without value) _UpperCAmelCase : int = True elif isclass(__UpperCAmelCase ) and issubclass(__UpperCAmelCase , __UpperCAmelCase ): _UpperCAmelCase : List[Any] = field.type.__args__[0] _UpperCAmelCase : Union[str, Any] = '+' if field.default_factory is not dataclasses.MISSING: _UpperCAmelCase : str = field.default_factory() elif field.default is dataclasses.MISSING: _UpperCAmelCase : Optional[Any] = True else: _UpperCAmelCase : Dict = field.type if field.default is not dataclasses.MISSING: _UpperCAmelCase : List[str] = field.default elif field.default_factory is not dataclasses.MISSING: _UpperCAmelCase : Optional[Any] = field.default_factory() else: _UpperCAmelCase : Optional[Any] = True parser.add_argument(__UpperCAmelCase , *__UpperCAmelCase , **__UpperCAmelCase ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): _UpperCAmelCase : int = False parser.add_argument(f'''--no_{field.name}''' , action="""store_false""" , dest=field.name , **__UpperCAmelCase ) def __snake_case ( self , _A ) -> Dict: '''simple docstring''' if hasattr(__UpperCAmelCase , """_argument_group_name""" ): _UpperCAmelCase : Optional[int] = self.add_argument_group(dtype._argument_group_name ) else: _UpperCAmelCase : Union[str, Any] = self try: _UpperCAmelCase : Dict[str, type] = get_type_hints(__UpperCAmelCase ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' """removing line of `from __future__ import annotations` which opts in Postponed """ """Evaluation of Annotations (PEP 563)""" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__UpperCAmelCase ): _UpperCAmelCase : Optional[int] = '.'.join(map(__UpperCAmelCase , sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' """line of `from __future__ import annotations` which opts in union types as """ """`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To """ """support Python versions that lower than 3.10, you need to use """ """`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of """ """`X | None`.""" ) from ex raise for field in dataclasses.fields(__UpperCAmelCase ): if not field.init: continue _UpperCAmelCase : List[Any] = type_hints[field.name] self._parse_dataclass_field(__UpperCAmelCase , __UpperCAmelCase ) def __snake_case ( self , _A=None , _A=False , _A=True , _A=None , _A=None , ) -> Tuple: '''simple docstring''' if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): _UpperCAmelCase : List[Any] = [] if args_filename: args_files.append(Path(__UpperCAmelCase ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(""".args""" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values _UpperCAmelCase : List[Any] = ArgumentParser() args_file_parser.add_argument(__UpperCAmelCase , type=__UpperCAmelCase , action="""append""" ) # Use only remaining args for further parsing (remove the args_file_flag) _UpperCAmelCase : Any = args_file_parser.parse_known_args(args=__UpperCAmelCase ) _UpperCAmelCase : Any = vars(__UpperCAmelCase ).get(args_file_flag.lstrip("""-""" ) , __UpperCAmelCase ) if cmd_args_file_paths: args_files.extend([Path(__UpperCAmelCase ) for p in cmd_args_file_paths] ) _UpperCAmelCase : Tuple = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last _UpperCAmelCase : List[str] = file_args + args if args is not None else file_args + sys.argv[1:] _UpperCAmelCase : str = self.parse_known_args(args=__UpperCAmelCase ) _UpperCAmelCase : List[str] = [] for dtype in self.dataclass_types: _UpperCAmelCase : List[Any] = {f.name for f in dataclasses.fields(__UpperCAmelCase ) if f.init} _UpperCAmelCase : Optional[Any] = {k: v for k, v in vars(__UpperCAmelCase ).items() if k in keys} for k in keys: delattr(__UpperCAmelCase , __UpperCAmelCase ) _UpperCAmelCase : Tuple = dtype(**__UpperCAmelCase ) outputs.append(__UpperCAmelCase ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(__UpperCAmelCase ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def __snake_case ( self , _A , _A = False ) -> int: '''simple docstring''' _UpperCAmelCase : str = set(args.keys() ) _UpperCAmelCase : Optional[Any] = [] for dtype in self.dataclass_types: _UpperCAmelCase : Any = {f.name for f in dataclasses.fields(__UpperCAmelCase ) if f.init} _UpperCAmelCase : str = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) _UpperCAmelCase : List[Any] = dtype(**__UpperCAmelCase ) outputs.append(__UpperCAmelCase ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(__UpperCAmelCase )}''' ) return tuple(__UpperCAmelCase ) def __snake_case ( self , _A , _A = False ) -> List[Any]: '''simple docstring''' with open(Path(__UpperCAmelCase ) , encoding="""utf-8""" ) as open_json_file: _UpperCAmelCase : Dict = json.loads(open_json_file.read() ) _UpperCAmelCase : int = self.parse_dict(__UpperCAmelCase , allow_extra_keys=__UpperCAmelCase ) return tuple(__UpperCAmelCase ) def __snake_case ( self , _A , _A = False ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase : List[str] = self.parse_dict(yaml.safe_load(Path(__UpperCAmelCase ).read_text() ) , allow_extra_keys=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
246
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Optional[int] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} UpperCAmelCase__ : int = { 'vocab_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/vocab.json', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/vocab.json', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/vocab.json', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/vocab.json', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/vocab.json', }, 'merges_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/merges.txt', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/merges.txt', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/merges.txt', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/merges.txt', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/merges.txt', }, 'tokenizer_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/tokenizer.json', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/tokenizer.json', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/tokenizer.json', }, } UpperCAmelCase__ : Optional[Any] = { 'gpt2': 1024, 'gpt2-medium': 1024, 'gpt2-large': 1024, 'gpt2-xl': 1024, 'distilgpt2': 1024, } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = VOCAB_FILES_NAMES __UpperCamelCase : str = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : int = ["""input_ids""", """attention_mask"""] __UpperCamelCase : Optional[Any] = GPTaTokenizer def __init__( self : str , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Optional[int]="<|endoftext|>" , lowerCAmelCase_ : List[str]="<|endoftext|>" , lowerCAmelCase_ : Dict="<|endoftext|>" , lowerCAmelCase_ : Dict=False , **lowerCAmelCase_ : Any , ): """simple docstring""" super().__init__( __UpperCAmelCase , __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , unk_token=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase , **__UpperCAmelCase , ) _A: List[str] = kwargs.pop('''add_bos_token''' , __UpperCAmelCase ) _A: Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __UpperCAmelCase ) != add_prefix_space: _A: Optional[Any] = getattr(__UpperCAmelCase , pre_tok_state.pop('''type''' ) ) _A: Optional[int] = add_prefix_space _A: Optional[Any] = pre_tok_class(**__UpperCAmelCase ) _A: int = add_prefix_space def __magic_name__ ( self : Dict , *lowerCAmelCase_ : Any , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[Any] = kwargs.get('''is_split_into_words''' , __UpperCAmelCase ) 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(*__UpperCAmelCase , **__UpperCAmelCase ) def __magic_name__ ( self : Dict , *lowerCAmelCase_ : Dict , **lowerCAmelCase_ : int ): """simple docstring""" _A: Optional[int] = kwargs.get('''is_split_into_words''' , __UpperCAmelCase ) 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(*__UpperCAmelCase , **__UpperCAmelCase ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[Any] = None ): """simple docstring""" _A: Dict = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Optional[int] ): """simple docstring""" _A: Tuple = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) + [self.eos_token_id] ) if len(__UpperCAmelCase ) > self.model_max_length: _A: Any = input_ids[-self.model_max_length :] return input_ids
121
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
0
import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class __lowerCAmelCase : def __init__( self :Optional[int] , __magic_name__ :List[Any] , __magic_name__ :str , __magic_name__ :Any = True , __magic_name__ :Optional[int] = False ): '''simple docstring''' a = scheduler a = optimizers if isinstance(__UpperCAmelCase , (list, tuple) ) else [optimizers] a = split_batches a = step_with_optimizer a = GradientState() def lowerCamelCase__ ( self :int , *__magic_name__ :int , **__magic_name__ :Tuple ): '''simple docstring''' if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step a = AcceleratorState().num_processes for _ in range(__UpperCAmelCase ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , """total_steps""" ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) else: self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' return self.scheduler.get_last_lr() def lowerCamelCase__ ( self :Any ): '''simple docstring''' return self.scheduler.state_dict() def lowerCamelCase__ ( self :int , __magic_name__ :Optional[Any] ): '''simple docstring''' self.scheduler.load_state_dict(__UpperCAmelCase ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' return self.scheduler.get_lr() def lowerCamelCase__ ( self :Any , *__magic_name__ :Optional[int] , **__magic_name__ :str ): '''simple docstring''' return self.scheduler.print_lr(*__UpperCAmelCase , **__UpperCAmelCase )
228
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class _snake_case : def __init__( self : str , UpperCAmelCase : List[str] ): __lowerCamelCase : Union[str, Any] = data __lowerCamelCase : List[Any] = [0X67_452_301, 0XEF_CDA_B89, 0X98_BAD_CFE, 0X10_325_476, 0XC3_D2E_1F0] @staticmethod def lowerCamelCase__ ( UpperCAmelCase : Any , UpperCAmelCase : Any ): return ((n << b) | (n >> (32 - b))) & 0XFF_FFF_FFF def lowerCamelCase__ ( self : List[Any] ): __lowerCamelCase : Dict = B'\x80' + B'\x00' * (63 - (len(self.data ) + 8) % 64) __lowerCamelCase : Any = self.data + padding + struct.pack(">Q" , 8 * len(self.data ) ) return padded_data def lowerCamelCase__ ( self : str ): return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : int ): __lowerCamelCase : int = list(struct.unpack(">16L" , __UpperCAmelCase ) ) + [0] * 64 for i in range(16 , 80 ): __lowerCamelCase : Any = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def lowerCamelCase__ ( self : List[Any] ): __lowerCamelCase : str = self.padding() __lowerCamelCase : List[str] = self.split_blocks() for block in self.blocks: __lowerCamelCase : int = self.expand_block(__UpperCAmelCase ) __lowerCamelCase : Any = self.h for i in range(0 , 80 ): if 0 <= i < 20: __lowerCamelCase : Tuple = (b & c) | ((~b) & d) __lowerCamelCase : Any = 0X5A_827_999 elif 20 <= i < 40: __lowerCamelCase : str = b ^ c ^ d __lowerCamelCase : Dict = 0X6E_D9E_BA1 elif 40 <= i < 60: __lowerCamelCase : Optional[int] = (b & c) | (b & d) | (c & d) __lowerCamelCase : str = 0X8F_1BB_CDC elif 60 <= i < 80: __lowerCamelCase : Optional[Any] = b ^ c ^ d __lowerCamelCase : Any = 0XCA_62C_1D6 __lowerCamelCase : Union[str, Any] = ( self.rotate(__UpperCAmelCase , 5 ) + f + e + k + expanded_block[i] & 0XFF_FFF_FFF, a, self.rotate(__UpperCAmelCase , 30 ), c, d, ) __lowerCamelCase : Dict = ( self.h[0] + a & 0XFF_FFF_FFF, self.h[1] + b & 0XFF_FFF_FFF, self.h[2] + c & 0XFF_FFF_FFF, self.h[3] + d & 0XFF_FFF_FFF, self.h[4] + e & 0XFF_FFF_FFF, ) return ("{:08x}" * 5).format(*self.h ) def lowercase_ ( ) -> Optional[Any]: '''simple docstring''' __lowerCamelCase : Dict = B'Test String' assert SHAaHash(_SCREAMING_SNAKE_CASE ).final_hash() == hashlib.shaa(_SCREAMING_SNAKE_CASE ).hexdigest() # noqa: S324 def lowercase_ ( ) -> Dict: '''simple docstring''' __lowerCamelCase : Union[str, Any] = argparse.ArgumentParser(description="Process some strings or files" ) parser.add_argument( "--string" , dest="input_string" , default="Hello World!! Welcome to Cryptography" , help="Hash the string" , ) parser.add_argument("--file" , dest="input_file" , help="Hash contents of a file" ) __lowerCamelCase : Dict = parser.parse_args() __lowerCamelCase : Optional[int] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , "rb" ) as f: __lowerCamelCase : List[Any] = f.read() else: __lowerCamelCase : int = bytes(_SCREAMING_SNAKE_CASE , "utf-8" ) print(SHAaHash(_SCREAMING_SNAKE_CASE ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
135
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
0
import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase, lowerCamelCase=None, lowerCamelCase=True, lowerCamelCase=None, **lowerCamelCase) -> Any: """simple docstring""" _lowercase : Dict = parent _lowercase : List[Any] = config_class _lowercase : List[Any] = has_text_modality _lowercase : str = kwargs _lowercase : Union[str, Any] = common_properties def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : int = self.config_class(**self.inputs_dict) _lowercase : Union[str, Any] = ( ['hidden_size', 'num_attention_heads', 'num_hidden_layers'] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(['vocab_size']) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(__UpperCAmelCase, __UpperCAmelCase), msg=F'''`{prop}` does not exist''') # Test that config has the common properties as setter for idx, name in enumerate(__UpperCAmelCase): try: setattr(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase) self.parent.assertEqual( getattr(__UpperCAmelCase, __UpperCAmelCase), __UpperCAmelCase, msg=F'''`{name} value {idx} expected, but was {getattr(__UpperCAmelCase, __UpperCAmelCase)}''') except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(__UpperCAmelCase): try: _lowercase : Any = self.config_class(**{name: idx}) self.parent.assertEqual( getattr(__UpperCAmelCase, __UpperCAmelCase), __UpperCAmelCase, msg=F'''`{name} value {idx} expected, but was {getattr(__UpperCAmelCase, __UpperCAmelCase)}''') except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" _lowercase : Optional[int] = self.config_class(**self.inputs_dict) _lowercase : Tuple = json.loads(config.to_json_string()) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key], __UpperCAmelCase) def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : Any = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : Optional[Any] = os.path.join(__UpperCAmelCase, 'config.json') config_first.to_json_file(__UpperCAmelCase) _lowercase : int = self.config_class.from_json_file(__UpperCAmelCase) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : Optional[Any] = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(__UpperCAmelCase) _lowercase : str = self.config_class.from_pretrained(__UpperCAmelCase) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : int = self.config_class(**self.inputs_dict) _lowercase : List[Any] = 'test' with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : Tuple = os.path.join(__UpperCAmelCase, __UpperCAmelCase) config_first.save_pretrained(__UpperCAmelCase) _lowercase : Optional[int] = self.config_class.from_pretrained(__UpperCAmelCase, subfolder=__UpperCAmelCase) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : str = self.config_class(**self.inputs_dict, num_labels=5) self.parent.assertEqual(len(config.idalabel), 5) self.parent.assertEqual(len(config.labelaid), 5) _lowercase : Any = 3 self.parent.assertEqual(len(config.idalabel), 3) self.parent.assertEqual(len(config.labelaid), 3) def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" if self.config_class.is_composition: return _lowercase : List[Any] = self.config_class() self.parent.assertIsNotNone(__UpperCAmelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Optional[Any] = copy.deepcopy(__UpperCAmelCase) _lowercase : Tuple = self.config_class(**__UpperCAmelCase) _lowercase : int = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa)) elif getattr(__UpperCAmelCase, __UpperCAmelCase) != value: wrong_values.append((key, getattr(__UpperCAmelCase, __UpperCAmelCase), value)) if len(__UpperCAmelCase) > 0: _lowercase : List[str] = '\n'.join([F'''- {v[0]}: got {v[1]} instead of {v[2]}''' for v in wrong_values]) raise ValueError(F'''The following keys were not properly set in the config:\n{errors}''') def UpperCamelCase ( self) -> List[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
21
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowerCamelCase = """rwkv""" _lowerCamelCase = {"""max_position_embeddings""": """context_length"""} def __init__( self , __lowerCamelCase=5_0277 , __lowerCamelCase=1024 , __lowerCamelCase=4096 , __lowerCamelCase=32 , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=1e-5 , __lowerCamelCase=0 , __lowerCamelCase=0 , __lowerCamelCase=6 , __lowerCamelCase=False , __lowerCamelCase=True , **__lowerCamelCase , ): '''simple docstring''' __A : Optional[int] = vocab_size __A : List[Any] = context_length __A : List[str] = hidden_size __A : Tuple = num_hidden_layers __A : List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size __A : Dict = intermediate_size if intermediate_size is not None else 4 * hidden_size __A : Union[str, Any] = layer_norm_epsilon __A : int = rescale_every __A : Dict = use_cache __A : Union[str, Any] = bos_token_id __A : List[str] = eos_token_id super().__init__( tie_word_embeddings=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase )
179
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() __a = logging.get_logger(__name__) def A_ ( _lowercase, _lowercase ): '''simple docstring''' snake_case_ :Dict = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f"""encoder.deit.blocks.{i}.norm1.weight""", f"""encoder.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""encoder.deit.blocks.{i}.norm1.bias""", f"""encoder.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.attn.proj.weight""", f"""encoder.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.attn.proj.bias""", f"""encoder.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.norm2.weight""", f"""encoder.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""encoder.deit.blocks.{i}.norm2.bias""", f"""encoder.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.mlp.fc1.weight""", f"""encoder.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.mlp.fc1.bias""", f"""encoder.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.mlp.fc2.weight""", f"""encoder.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""encoder.deit.blocks.{i}.mlp.fc2.bias""", f"""encoder.encoder.layer.{i}.output.dense.bias""") ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ("""encoder.deit.cls_token""", """encoder.embeddings.cls_token"""), ("""encoder.deit.pos_embed""", """encoder.embeddings.position_embeddings"""), ("""encoder.deit.patch_embed.proj.weight""", """encoder.embeddings.patch_embeddings.projection.weight"""), ("""encoder.deit.patch_embed.proj.bias""", """encoder.embeddings.patch_embeddings.projection.bias"""), ("""encoder.deit.norm.weight""", """encoder.layernorm.weight"""), ("""encoder.deit.norm.bias""", """encoder.layernorm.bias"""), ] ) return rename_keys def A_ ( _lowercase, _lowercase ): '''simple docstring''' for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) snake_case_ :str = state_dict.pop(f"""encoder.deit.blocks.{i}.attn.qkv.weight""" ) snake_case_ :Dict = in_proj_weight[ : encoder_config.hidden_size, : ] snake_case_ :Dict = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] snake_case_ :Tuple = in_proj_weight[ -encoder_config.hidden_size :, : ] def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' snake_case_ :List[Any] = dct.pop(_SCREAMING_SNAKE_CASE ) snake_case_ :Dict = val def A_ ( _lowercase ): '''simple docstring''' if "handwritten" in checkpoint_url: snake_case_ :Tuple = 'https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg' # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: snake_case_ :Any = 'https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg' snake_case_ :str = Image.open(requests.get(_SCREAMING_SNAKE_CASE, stream=_SCREAMING_SNAKE_CASE ).raw ).convert("""RGB""" ) return im @torch.no_grad() def A_ ( _lowercase, _lowercase ): '''simple docstring''' snake_case_ :List[Any] = ViTConfig(image_size=384, qkv_bias=_SCREAMING_SNAKE_CASE ) snake_case_ :Tuple = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: snake_case_ :int = 768 elif "large" in checkpoint_url: # use ViT-large encoder snake_case_ :str = 1024 snake_case_ :Optional[int] = 4096 snake_case_ :Tuple = 24 snake_case_ :List[Any] = 16 snake_case_ :Optional[Any] = 1024 else: raise ValueError("""Should either find \'base\' or \'large\' in checkpoint URL""" ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: snake_case_ :Optional[Any] = False snake_case_ :Optional[Any] = 'relu' snake_case_ :Any = 1024 snake_case_ :List[Any] = True snake_case_ :Dict = False snake_case_ :Optional[Any] = False # load HuggingFace model snake_case_ :str = ViTModel(_SCREAMING_SNAKE_CASE, add_pooling_layer=_SCREAMING_SNAKE_CASE ) snake_case_ :int = TrOCRForCausalLM(_SCREAMING_SNAKE_CASE ) snake_case_ :List[Any] = VisionEncoderDecoderModel(encoder=_SCREAMING_SNAKE_CASE, decoder=_SCREAMING_SNAKE_CASE ) model.eval() # load state_dict of original model, rename some keys snake_case_ :Optional[Any] = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE, map_location="""cpu""", check_hash=_SCREAMING_SNAKE_CASE )['model'] snake_case_ :Union[str, Any] = create_rename_keys(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): snake_case_ :List[Any] = state_dict.pop(_SCREAMING_SNAKE_CASE ) if key.startswith("""decoder""" ) and "output_projection" not in key: snake_case_ :List[Any] = val else: snake_case_ :Dict = val # load state dict model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image snake_case_ :Optional[Any] = ViTImageProcessor(size=encoder_config.image_size ) snake_case_ :Dict = RobertaTokenizer.from_pretrained("""roberta-large""" ) snake_case_ :List[str] = TrOCRProcessor(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) snake_case_ :Optional[Any] = processor(images=prepare_img(_SCREAMING_SNAKE_CASE ), return_tensors="""pt""" ).pixel_values # verify logits snake_case_ :List[str] = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) snake_case_ :List[Any] = model(pixel_values=_SCREAMING_SNAKE_CASE, decoder_input_ids=_SCREAMING_SNAKE_CASE ) snake_case_ :Dict = outputs.logits snake_case_ :Dict = torch.Size([1, 1, 50265] ) if "trocr-base-handwritten" in checkpoint_url: snake_case_ :Optional[Any] = torch.tensor( [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] ) elif "trocr-large-handwritten" in checkpoint_url: snake_case_ :Tuple = torch.tensor( [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170] ) elif "trocr-base-printed" in checkpoint_url: snake_case_ :Dict = torch.tensor( [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] ) elif "trocr-large-printed" in checkpoint_url: snake_case_ :Optional[Any] = torch.tensor( [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10], _SCREAMING_SNAKE_CASE, atol=1e-3 ), "First elements of logits not as expected" Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt", 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." ) __a = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
66
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
0
import os import unicodedata 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 lowercase__ : Optional[int] = logging.get_logger(__name__) lowercase__ : Any = {"vocab_file": "spiece.model"} lowercase__ : Union[str, Any] = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } lowercase__ : str = { "albert-base-v1": 5_1_2, "albert-large-v1": 5_1_2, "albert-xlarge-v1": 5_1_2, "albert-xxlarge-v1": 5_1_2, "albert-base-v2": 5_1_2, "albert-large-v2": 5_1_2, "albert-xlarge-v2": 5_1_2, "albert-xxlarge-v2": 5_1_2, } lowercase__ : Optional[int] = "▁" class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" _snake_case = VOCAB_FILES_NAMES _snake_case = PRETRAINED_VOCAB_FILES_MAP _snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , )-> Any: '''simple docstring''' __UpperCamelCase = ( AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase , normalized=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token ) __UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) __UpperCamelCase = do_lower_case __UpperCamelCase = remove_space __UpperCamelCase = keep_accents __UpperCamelCase = vocab_file __UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) @property def A__ ( self )-> Tuple: '''simple docstring''' return len(self.sp_model ) def A__ ( self )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> int: '''simple docstring''' __UpperCamelCase = self.__dict__.copy() __UpperCamelCase = None return state def __setstate__( self , SCREAMING_SNAKE_CASE_ )-> Tuple: '''simple docstring''' __UpperCamelCase = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __UpperCamelCase = {} __UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Optional[int]: '''simple docstring''' if self.remove_space: __UpperCamelCase = ' '.join(inputs.strip().split() ) else: __UpperCamelCase = inputs __UpperCamelCase = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: __UpperCamelCase = unicodedata.normalize('''NFKD''' , __UpperCAmelCase ) __UpperCamelCase = ''.join([c for c in outputs if not unicodedata.combining(__UpperCAmelCase )] ) if self.do_lower_case: __UpperCamelCase = outputs.lower() return outputs def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = self.preprocess_text(__UpperCAmelCase ) __UpperCamelCase = self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) __UpperCamelCase = [] for piece in pieces: if len(__UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): __UpperCamelCase = self.sp_model.EncodeAsPieces(piece[:-1].replace(__UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __UpperCamelCase = cur_pieces[1:] else: __UpperCamelCase = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__UpperCAmelCase ) else: new_pieces.append(__UpperCAmelCase ) return new_pieces def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Tuple: '''simple docstring''' return self.sp_model.PieceToId(__UpperCAmelCase ) def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Dict: '''simple docstring''' return self.sp_model.IdToPiece(__UpperCAmelCase ) def A__ ( self , SCREAMING_SNAKE_CASE_ )-> str: '''simple docstring''' __UpperCamelCase = [] __UpperCamelCase = '' __UpperCamelCase = 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 __UpperCamelCase = True __UpperCamelCase = [] else: current_sub_tokens.append(__UpperCAmelCase ) __UpperCamelCase = False out_string += self.sp_model.decode(__UpperCAmelCase ) return out_string.strip() def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None )-> Optional[Any]: '''simple docstring''' __UpperCamelCase = [self.sep_token_id] __UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False )-> Any: '''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 not None: return [1] + ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1] return [1] + ([0] * len(__UpperCAmelCase )) + [1] def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = [self.sep_token_id] __UpperCamelCase = [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 A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None )-> str: '''simple docstring''' if not os.path.isdir(__UpperCAmelCase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __UpperCamelCase = 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: __UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,)
328
"""simple docstring""" import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
0
from statistics import mean import numpy as np def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase): UpperCamelCase_ = 0 # Number of processes finished UpperCamelCase_ = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. UpperCamelCase_ = [0] * no_of_process # List to include calculation results UpperCamelCase_ = [0] * no_of_process # Sort by arrival time. UpperCamelCase_ = [burst_time[i] for i in np.argsort(_SCREAMING_SNAKE_CASE)] UpperCamelCase_ = [process_name[i] for i in np.argsort(_SCREAMING_SNAKE_CASE)] arrival_time.sort() while no_of_process > finished_process_count: UpperCamelCase_ = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: UpperCamelCase_ = arrival_time[i] UpperCamelCase_ = 0 # Index showing the location of the process being performed UpperCamelCase_ = 0 # Saves the current response ratio. UpperCamelCase_ = 0 for i in range(0 , _SCREAMING_SNAKE_CASE): if finished_process[i] == 0 and arrival_time[i] <= current_time: UpperCamelCase_ = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: UpperCamelCase_ = temp UpperCamelCase_ = i # Calculate the turn around time UpperCamelCase_ = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. UpperCamelCase_ = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase): UpperCamelCase_ = [0] * no_of_process for i in range(0 , _SCREAMING_SNAKE_CASE): UpperCamelCase_ = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": UpperCAmelCase : Union[str, Any] =5 UpperCAmelCase : Union[str, Any] =["""A""", """B""", """C""", """D""", """E"""] UpperCAmelCase : Dict =[1, 2, 3, 4, 5] UpperCAmelCase : Optional[Any] =[1, 2, 3, 4, 5] UpperCAmelCase : List[Any] =calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) UpperCAmelCase : List[str] =calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("""Process name \tArrival time \tBurst time \tTurn around time \tWaiting time""") for i in range(0, no_of_process): print( F"{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t" F"{turn_around_time[i]}\t\t\t{waiting_time[i]}" ) print(F"average waiting time : {mean(waiting_time):.5f}") print(F"average turn around time : {mean(turn_around_time):.5f}")
128
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { "configuration_pegasus_x": ["PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP", "PegasusXConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST", "PegasusXForConditionalGeneration", "PegasusXModel", "PegasusXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
10
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
0
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time SCREAMING_SNAKE_CASE__ = Lock() def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase = 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 UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Dict ): '''simple docstring''' lowerCAmelCase = [] lowerCAmelCase = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase = Pipe() lowerCAmelCase = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase = temp_rs lowerCAmelCase = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase = Pipe() lowerCAmelCase = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase = temp_rs lowerCAmelCase = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase = result_pipe[p][0].recv() process_array_[p].join() return arr def UpperCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase = list(range(10 , 0 , -1 ) ) print("""Initial List""" ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print("""Sorted List\n""" ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
46
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
0
"""simple docstring""" from __future__ import annotations lowerCamelCase__ : List[str] = tuple[int, int, int] lowerCamelCase__ : List[str] = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase lowerCamelCase__ : str = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' # -------------------------- default selection -------------------------- # rotors -------------------------- lowerCamelCase__ : Optional[Any] = '''EGZWVONAHDCLFQMSIPJBYUKXTR''' lowerCamelCase__ : Tuple = '''FOBHMDKEXQNRAULPGSJVTYICZW''' lowerCamelCase__ : str = '''ZJXESIUQLHAVRMDOYGTNFWPBKC''' # reflector -------------------------- lowerCamelCase__ : List[str] = { '''A''': '''N''', '''N''': '''A''', '''B''': '''O''', '''O''': '''B''', '''C''': '''P''', '''P''': '''C''', '''D''': '''Q''', '''Q''': '''D''', '''E''': '''R''', '''R''': '''E''', '''F''': '''S''', '''S''': '''F''', '''G''': '''T''', '''T''': '''G''', '''H''': '''U''', '''U''': '''H''', '''I''': '''V''', '''V''': '''I''', '''J''': '''W''', '''W''': '''J''', '''K''': '''X''', '''X''': '''K''', '''L''': '''Y''', '''Y''': '''L''', '''M''': '''Z''', '''Z''': '''M''', } # -------------------------- extra rotors -------------------------- lowerCamelCase__ : Optional[Any] = '''RMDJXFUWGISLHVTCQNKYPBEZOA''' lowerCamelCase__ : Dict = '''SGLCPQWZHKXAREONTFBVIYJUDM''' lowerCamelCase__ : Union[str, Any] = '''HVSICLTYKQUBXDWAJZOMFGPREN''' lowerCamelCase__ : List[Any] = '''RZWQHFMVDBKICJLNTUXAGYPSOE''' lowerCamelCase__ : Optional[int] = '''LFKIJODBEGAMQPXVUHYSTCZRWN''' lowerCamelCase__ : Any = '''KOAEGVDHXPQZMLFTYWJNBRCIUS''' def UpperCamelCase ( _lowerCAmelCase : Tuple, _lowerCAmelCase : Tuple, _lowerCAmelCase : List[Any] ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: _UpperCAmelCase : Union[str, Any] = f'''Please use 3 unique rotors (not {unique_rotsel})''' raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid _UpperCAmelCase : str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Tuple = f'''First rotor position is not within range of 1..26 ({rotorposa}''' raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = f'''Second rotor position is not within range of 1..26 ({rotorposa})''' raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = f'''Third rotor position is not within range of 1..26 ({rotorposa})''' raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict _UpperCAmelCase : int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def UpperCamelCase ( _lowerCAmelCase : Any ) -> dict[str, str]: if not isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): _UpperCAmelCase : str = f'''Plugboard setting isn\'t type string ({type(_SCREAMING_SNAKE_CASE )})''' raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: _UpperCAmelCase : str = f'''Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})''' raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(""" """, """""" ) # Checks if all characters are unique _UpperCAmelCase : Any = set() for i in pbstring: if i not in abc: _UpperCAmelCase : Any = f'''\'{i}\' not in list of symbols''' raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: _UpperCAmelCase : Dict = f'''Duplicate symbol ({i})''' raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary _UpperCAmelCase : List[Any] = {} for j in range(0, len(_SCREAMING_SNAKE_CASE ) - 1, 2 ): _UpperCAmelCase : Optional[int] = pbstring[j + 1] _UpperCAmelCase : Union[str, Any] = pbstring[j] return pb def UpperCamelCase ( _lowerCAmelCase : Optional[Any], _lowerCAmelCase : List[Any], _lowerCAmelCase : Tuple = (rotora, rotora, rotora), _lowerCAmelCase : Optional[int] = "", ) -> str: _UpperCAmelCase : Tuple = text.upper() _UpperCAmelCase : Tuple = _validator( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, plugb.upper() ) _UpperCAmelCase : Tuple = rotor_position _UpperCAmelCase : Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 _UpperCAmelCase : Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: _UpperCAmelCase : Dict = plugboard[symbol] # rotor ra -------------------------- _UpperCAmelCase : Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa _UpperCAmelCase : str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- _UpperCAmelCase : Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa _UpperCAmelCase : int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- _UpperCAmelCase : str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa _UpperCAmelCase : Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher _UpperCAmelCase : str = reflector[symbol] # 2nd rotors _UpperCAmelCase : Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] _UpperCAmelCase : Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] _UpperCAmelCase : Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: _UpperCAmelCase : Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCamelCase__ : int = '''This is my Python script that emulates the Enigma machine from WWII.''' lowerCamelCase__ : Union[str, Any] = (1, 1, 1) lowerCamelCase__ : Tuple = '''pictures''' lowerCamelCase__ : int = (rotora, rotora, rotora) lowerCamelCase__ : List[str] = enigma(message, rotor_pos, rotor_sel, pb) print('''Encrypted message:''', en) print('''Decrypted message:''', enigma(en, rotor_pos, rotor_sel, pb))
246
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
0
from __future__ import annotations from statistics import mean def lowerCamelCase__ ( a , a , a ) -> list[int]: _A: Optional[int] = [0] * no_of_processes _A: str = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(_SCREAMING_SNAKE_CASE ): _A: Any = burst_time[i] _A: list[int] = [] _A: Optional[Any] = 0 _A: Optional[int] = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: _A: List[Any] = [] _A: int = -1 for i in range(_SCREAMING_SNAKE_CASE ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: _A: int = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: _A: Dict = i total_time += burst_time[target_process] completed += 1 _A: Tuple = 0 _A: List[str] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def lowerCamelCase__ ( a , a , a ) -> list[int]: _A: Optional[Any] = [0] * no_of_processes for i in range(_SCREAMING_SNAKE_CASE ): _A: str = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print('[TEST CASE 01]') UpperCAmelCase__ : str = 4 UpperCAmelCase__ : Dict = [2, 5, 3, 7] UpperCAmelCase__ : str = [0, 0, 0, 0] UpperCAmelCase__ : Dict = calculate_waitingtime(arrival_time, burst_time, no_of_processes) UpperCAmelCase__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print('PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time') for i, process_id in enumerate(list(range(1, 5))): print( F"""{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t""" F"""{waiting_time[i]}\t\t\t\t{turn_around_time[i]}""" ) print(F"""\nAverage waiting time = {mean(waiting_time):.5f}""") print(F"""Average turnaround time = {mean(turn_around_time):.5f}""")
121
"""simple docstring""" from __future__ import annotations __A = tuple[int, int, int] __A = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __A = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __A = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __A = """FOBHMDKEXQNRAULPGSJVTYICZW""" __A = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __A = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __A = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __A = """SGLCPQWZHKXAREONTFBVIYJUDM""" __A = """HVSICLTYKQUBXDWAJZOMFGPREN""" __A = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __A = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __A = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """simple docstring""" if (unique_rotsel := len(set(_SCREAMING_SNAKE_CASE ) )) < 3: lowerCAmelCase__ :Union[str, Any] = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_SCREAMING_SNAKE_CASE ) # Checks if rotor positions are valid lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = rotpos if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Tuple = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) if not 0 < rotorposa <= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_SCREAMING_SNAKE_CASE ) # Validates string and returns dict lowerCAmelCase__ :int = _plugboard(_SCREAMING_SNAKE_CASE ) return rotpos, rotsel, pbdict def __A (_SCREAMING_SNAKE_CASE ) ->dict[str, str]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = F"Plugboard setting isn't type string ({type(_SCREAMING_SNAKE_CASE )})" raise TypeError(_SCREAMING_SNAKE_CASE ) elif len(_SCREAMING_SNAKE_CASE ) % 2 != 0: lowerCAmelCase__ :str = F"Odd number of symbols ({len(_SCREAMING_SNAKE_CASE )})" raise Exception(_SCREAMING_SNAKE_CASE ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCAmelCase__ :Any = set() for i in pbstring: if i not in abc: lowerCAmelCase__ :Any = F"'{i}' not in list of symbols" raise Exception(_SCREAMING_SNAKE_CASE ) elif i in tmppbl: lowerCAmelCase__ :Dict = F"Duplicate symbol ({i})" raise Exception(_SCREAMING_SNAKE_CASE ) else: tmppbl.add(_SCREAMING_SNAKE_CASE ) del tmppbl # Created the dictionary lowerCAmelCase__ :List[Any] = {} for j in range(0 , len(_SCREAMING_SNAKE_CASE ) - 1 , 2 ): lowerCAmelCase__ :Optional[int] = pbstring[j + 1] lowerCAmelCase__ :Union[str, Any] = pbstring[j] return pb def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (rotora, rotora, rotora) , _SCREAMING_SNAKE_CASE = "" , ) ->str: """simple docstring""" lowerCAmelCase__ :Tuple = text.upper() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = _validator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , plugb.upper() ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = rotor_position lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCAmelCase__ :Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCAmelCase__ :Dict = plugboard[symbol] # rotor ra -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :str = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rb -------------------------- lowerCAmelCase__ :Optional[int] = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :int = rotora[index % len(_SCREAMING_SNAKE_CASE )] # rotor rc -------------------------- lowerCAmelCase__ :str = abc.index(_SCREAMING_SNAKE_CASE ) + rotorposa lowerCAmelCase__ :Optional[Any] = rotora[index % len(_SCREAMING_SNAKE_CASE )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCAmelCase__ :str = reflector[symbol] # 2nd rotors lowerCAmelCase__ :Tuple = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Optional[int] = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] lowerCAmelCase__ :Any = abc[rotora.index(_SCREAMING_SNAKE_CASE ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCAmelCase__ :Union[str, Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :str = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :List[Any] = 0 rotorposa += 1 if rotorposa >= len(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = """This is my Python script that emulates the Enigma machine from WWII.""" __A = (1, 1, 1) __A = """pictures""" __A = (rotora, rotora, rotora) __A = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
293
0
def __A ( ) -> Dict: a = 0 for i in range(1 , 1001 ): total += i**i return str(_SCREAMING_SNAKE_CASE )[-10:] if __name__ == "__main__": print(solution())
228
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
0
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: __A = None __A = logging.get_logger(__name__) __A = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} __A = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json''', }, } __A = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } __A = '''▁''' # Segments (not really needed) __A = 0 __A = 1 __A = 2 __A = 3 __A = 4 class _snake_case ( a__ ): snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = """left""" snake_case__ = XLNetTokenizer def __init__( self : Tuple , UpperCAmelCase : str=None , UpperCAmelCase : List[Any]=None , UpperCAmelCase : Tuple=False , UpperCAmelCase : Tuple=True , UpperCAmelCase : List[Any]=False , UpperCAmelCase : str="<s>" , UpperCAmelCase : int="</s>" , UpperCAmelCase : Tuple="<unk>" , UpperCAmelCase : Any="<sep>" , UpperCAmelCase : str="<pad>" , UpperCAmelCase : Union[str, Any]="<cls>" , UpperCAmelCase : Union[str, Any]="<mask>" , UpperCAmelCase : Optional[int]=["<eop>", "<eod>"] , **UpperCAmelCase : Any , ): __lowerCamelCase : Optional[int] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token super().__init__( vocab_file=__UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) __lowerCamelCase : Optional[Any] = 3 __lowerCamelCase : Dict = do_lower_case __lowerCamelCase : Optional[Any] = remove_space __lowerCamelCase : Union[str, Any] = keep_accents __lowerCamelCase : Optional[Any] = vocab_file __lowerCamelCase : List[str] = False if not self.vocab_file else True def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[Any] = None ): __lowerCamelCase : Optional[int] = [self.sep_token_id] __lowerCamelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def lowerCamelCase__ ( self : Tuple , UpperCAmelCase : Any , UpperCAmelCase : List[Any] = None ): __lowerCamelCase : str = [self.sep_token_id] __lowerCamelCase : List[str] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def lowerCamelCase__ ( self : List[str] , UpperCAmelCase : Any , UpperCAmelCase : int = None ): if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase : List[str] = os.path.join( __UpperCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) return (out_vocab_file,)
135
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCAmelCase__ :Union[str, Any] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_SCREAMING_SNAKE_CASE ) ) return round(_SCREAMING_SNAKE_CASE , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase = None, ) -> Optional[int]: """simple docstring""" super().__init__() self.register_modules(transformer=__UpperCAmelCase, vae=__UpperCAmelCase, scheduler=__UpperCAmelCase) # create a imagenet -> id dictionary for easier use _lowercase : Optional[int] = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(','): _lowercase : Dict = int(__UpperCAmelCase) _lowercase : Any = dict(sorted(self.labels.items())) def UpperCamelCase ( self, lowerCamelCase) -> str: """simple docstring""" if not isinstance(__UpperCAmelCase, __UpperCAmelCase): _lowercase : Optional[int] = list(__UpperCAmelCase) for l in label: if l not in self.labels: raise ValueError( F'''{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.''') return [self.labels[l] for l in label] @torch.no_grad() def __call__( self, lowerCamelCase, lowerCamelCase = 4.0, lowerCamelCase = None, lowerCamelCase = 50, lowerCamelCase = "pil", lowerCamelCase = True, ) -> List[Any]: """simple docstring""" _lowercase : Optional[Any] = len(__UpperCAmelCase) _lowercase : Tuple = self.transformer.config.sample_size _lowercase : Union[str, Any] = self.transformer.config.in_channels _lowercase : Any = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size), generator=__UpperCAmelCase, device=self.device, dtype=self.transformer.dtype, ) _lowercase : Tuple = torch.cat([latents] * 2) if guidance_scale > 1 else latents _lowercase : Tuple = torch.tensor(__UpperCAmelCase, device=self.device).reshape(-1) _lowercase : Optional[int] = torch.tensor([10_00] * batch_size, device=self.device) _lowercase : int = torch.cat([class_labels, class_null], 0) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(__UpperCAmelCase) for t in self.progress_bar(self.scheduler.timesteps): if guidance_scale > 1: _lowercase : Tuple = latent_model_input[: len(__UpperCAmelCase) // 2] _lowercase : List[str] = torch.cat([half, half], dim=0) _lowercase : List[str] = self.scheduler.scale_model_input(__UpperCAmelCase, __UpperCAmelCase) _lowercase : Tuple = t if not torch.is_tensor(__UpperCAmelCase): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) _lowercase : List[str] = latent_model_input.device.type == 'mps' if isinstance(__UpperCAmelCase, __UpperCAmelCase): _lowercase : List[str] = torch.floataa if is_mps else torch.floataa else: _lowercase : List[str] = torch.intaa if is_mps else torch.intaa _lowercase : Optional[Any] = torch.tensor([timesteps], dtype=__UpperCAmelCase, device=latent_model_input.device) elif len(timesteps.shape) == 0: _lowercase : Optional[int] = timesteps[None].to(latent_model_input.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _lowercase : Optional[int] = timesteps.expand(latent_model_input.shape[0]) # predict noise model_output _lowercase : Optional[int] = self.transformer( __UpperCAmelCase, timestep=__UpperCAmelCase, class_labels=__UpperCAmelCase).sample # perform guidance if guidance_scale > 1: _lowercase : Any = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] _lowercase : Union[str, Any] = torch.split(__UpperCAmelCase, len(__UpperCAmelCase) // 2, dim=0) _lowercase : Any = uncond_eps + guidance_scale * (cond_eps - uncond_eps) _lowercase : int = torch.cat([half_eps, half_eps], dim=0) _lowercase : Union[str, Any] = torch.cat([eps, rest], dim=1) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: _lowercase : List[str] = torch.split(__UpperCAmelCase, __UpperCAmelCase, dim=1) else: _lowercase : str = noise_pred # compute previous image: x_t -> x_t-1 _lowercase : Dict = self.scheduler.step(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase).prev_sample if guidance_scale > 1: _lowercase : str = latent_model_input.chunk(2, dim=0) else: _lowercase : Optional[int] = latent_model_input _lowercase : Tuple = 1 / self.vae.config.scaling_factor * latents _lowercase : Dict = self.vae.decode(__UpperCAmelCase).sample _lowercase : Union[str, Any] = (samples / 2 + 0.5).clamp(0, 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 _lowercase : List[str] = samples.cpu().permute(0, 2, 3, 1).float().numpy() if output_type == "pil": _lowercase : int = self.numpy_to_pil(__UpperCAmelCase) if not return_dict: return (samples,) return ImagePipelineOutput(images=__UpperCAmelCase)
21
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""OwlViTFeatureExtractor"""] __A = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
"""simple docstring""" import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput a_ = """scheduler_config.json""" class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowerCamelCase = 1 _lowerCamelCase = 2 _lowerCamelCase = 3 _lowerCamelCase = 4 _lowerCamelCase = 5 _lowerCamelCase = 6 _lowerCamelCase = 7 _lowerCamelCase = 8 _lowerCamelCase = 9 _lowerCamelCase = 10 _lowerCamelCase = 11 _lowerCamelCase = 12 _lowerCamelCase = 13 _lowerCamelCase = 14 @dataclass class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowerCamelCase = 42 class __snake_case : """simple docstring""" _lowerCamelCase = SCHEDULER_CONFIG_NAME _lowerCamelCase = [] _lowerCamelCase = True @classmethod def UpperCamelCase__( cls , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=False , **__lowerCamelCase , ): '''simple docstring''' __A : Optional[int] = cls.load_config( pretrained_model_name_or_path=__UpperCAmelCase , subfolder=__UpperCAmelCase , return_unused_kwargs=__UpperCAmelCase , return_commit_hash=__UpperCAmelCase , **__UpperCAmelCase , ) return cls.from_config(__UpperCAmelCase , return_unused_kwargs=__UpperCAmelCase , **__UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase = False , **__lowerCamelCase ): '''simple docstring''' self.save_config(save_directory=__UpperCAmelCase , push_to_hub=__UpperCAmelCase , **__UpperCAmelCase ) @property def UpperCamelCase__( self ): '''simple docstring''' return self._get_compatibles() @classmethod def UpperCamelCase__( cls ): '''simple docstring''' __A : Union[str, Any] = list(set([cls.__name__] + cls._compatibles ) ) __A : Any = importlib.import_module(__name__.split('''.''' )[0] ) __A : List[Any] = [ getattr(__UpperCAmelCase , __UpperCAmelCase ) for c in compatible_classes_str if hasattr(__UpperCAmelCase , __UpperCAmelCase ) ] return compatible_classes
179
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _lowerCAmelCase : """simple docstring""" @staticmethod def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' pass def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __A = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __magic_name__ :str = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = pipeline( 'document-question-answering' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) lowerCAmelCase__ :List[Any] = 'What is the placebo?' lowerCAmelCase__ :Dict = [ { 'image': load_image(__UpperCAmelCase ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = dqa_pipeline(__UpperCAmelCase , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, {'score': ANY(__UpperCAmelCase ), 'answer': ANY(__UpperCAmelCase ), 'start': ANY(__UpperCAmelCase ), 'end': ANY(__UpperCAmelCase )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCAmelCase__ :Union[str, Any] = INVOICE_URL lowerCAmelCase__ :Tuple = 'How many cats are there?' lowerCAmelCase__ :List[str] = [ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0}, ] lowerCAmelCase__ :Any = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) lowerCAmelCase__ :Any = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , __UpperCAmelCase ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase__ :List[Any] = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase__ :Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' lowerCAmelCase__ :List[str] = [] lowerCAmelCase__ :int = [] lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , words=__UpperCAmelCase , boxes=__UpperCAmelCase , top_k=2 ) self.assertEqual(__UpperCAmelCase , [] ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCAmelCase__ :str = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Union[str, Any] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :Dict = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.00_09, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=5_0 , ) lowerCAmelCase__ :List[Any] = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :Optional[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :int = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, {'score': 0.99_48, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , ) lowerCAmelCase__ :List[str] = INVOICE_URL lowerCAmelCase__ :Any = 'What is the invoice number?' lowerCAmelCase__ :List[Any] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :Optional[int] = dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] ] * 2 , ) lowerCAmelCase__ :Dict = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :Tuple = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.08_19, 'answer': '1110212019', 'start': 2_3, 'end': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=__UpperCAmelCase , revision='3dc6de3' , max_seq_len=5_0 , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :List[Any] = 'What is the invoice number?' lowerCAmelCase__ :List[str] = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) lowerCAmelCase__ :List[str] = dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] ] * 2 , ) lowerCAmelCase__ :Optional[Any] = list(zip(*apply_tesseract(load_image(__UpperCAmelCase ) , __UpperCAmelCase , '' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase__ :List[str] = dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, {'score': 0.99_98, 'answer': 'us-001', 'start': 1_6, 'end': 1_6}, ] , ) @slow @require_torch def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = pipeline( 'document-question-answering' , model='naver-clova-ix/donut-base-finetuned-docvqa' , tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa' ) , feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa' , ) lowerCAmelCase__ :Dict = INVOICE_URL lowerCAmelCase__ :str = 'What is the invoice number?' lowerCAmelCase__ :Tuple = dqa_pipeline(image=__UpperCAmelCase , question=__UpperCAmelCase , top_k=2 ) self.assertEqual(nested_simplify(__UpperCAmelCase , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def snake_case ( self ): '''simple docstring''' pass
293
0
"""simple docstring""" from torch import nn def A_ ( _lowercase ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f"""Unsupported activation function: {act_fn}""" )
66
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Tuple = StableDiffusionXLImgaImgPipeline __magic_name__ :List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} __magic_name__ :Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} __magic_name__ :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __magic_name__ :str = IMAGE_TO_IMAGE_IMAGE_PARAMS __magic_name__ :Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__UpperCAmelCase , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase__ :str = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) lowerCAmelCase__ :int = CLIPTextModel(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :Any = CLIPTextModelWithProjection(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__UpperCAmelCase ) lowerCAmelCase__ :str = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image / 2 + 0.5 if str(__UpperCAmelCase ).startswith('mps' ): lowerCAmelCase__ :Optional[int] = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ :Optional[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ :int = self.get_dummy_components() lowerCAmelCase__ :List[str] = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :str = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = sd_pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase__ :List[str] = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_dummy_components() lowerCAmelCase__ :str = StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe.to(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # forward without prompt embeds lowerCAmelCase__ :int = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = 3 * ['this is a negative prompt'] lowerCAmelCase__ :Tuple = negative_prompt lowerCAmelCase__ :str = 3 * [inputs['prompt']] lowerCAmelCase__ :Optional[Any] = sd_pipe(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = 3 * ['this is a negative prompt'] lowerCAmelCase__ :str = 3 * [inputs.pop('prompt' )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) :List[str] = sd_pipe.encode_prompt(__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) lowerCAmelCase__ :str = sd_pipe( **__UpperCAmelCase , prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , pooled_prompt_embeds=__UpperCAmelCase , negative_pooled_prompt_embeds=__UpperCAmelCase , ) lowerCAmelCase__ :Optional[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase="cpu" , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ): '''simple docstring''' lowerCAmelCase__ :Any = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ :Dict = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase__ :Optional[int] = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) lowerCAmelCase__ :int = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = self.get_inputs(__UpperCAmelCase ) lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :List[str] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
293
0
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def A_ ( snake_case : List[Any] , snake_case : List[Any] , snake_case : Union[str, Any]=None , snake_case : Optional[int]=None ) -> List[Any]: '''simple docstring''' if attention_mask is None: __UpperCamelCase = tf.cast(tf.math.not_equal(_SCREAMING_SNAKE_CASE , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class SCREAMING_SNAKE_CASE__ : """simple docstring""" _snake_case = OPTConfig _snake_case = {} _snake_case = """gelu""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=20 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=16 , )-> List[str]: '''simple docstring''' __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id __UpperCamelCase = embed_dim __UpperCamelCase = word_embed_proj_dim __UpperCamelCase = False def A__ ( self )-> Union[str, Any]: '''simple docstring''' __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=__UpperCAmelCase , **self.config_updates , ) __UpperCamelCase = prepare_opt_inputs_dict(__UpperCAmelCase , __UpperCAmelCase ) return config, inputs_dict def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> str: '''simple docstring''' __UpperCamelCase = TFOPTModel(config=__UpperCAmelCase ) __UpperCamelCase = inputs_dict['input_ids'] __UpperCamelCase = input_ids[:1, :] __UpperCamelCase = inputs_dict['attention_mask'][:1, :] __UpperCamelCase = 1 # first forward pass __UpperCamelCase = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase ) __UpperCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __UpperCamelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) __UpperCamelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __UpperCamelCase = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase )[0] __UpperCamelCase = 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 __UpperCamelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx] __UpperCamelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-3 ) @require_tf class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" _snake_case = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () _snake_case = (TFOPTForCausalLM,) if is_tf_available() else () _snake_case = ( {"""feature-extraction""": TFOPTModel, """text-generation""": TFOPTForCausalLM} if is_tf_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = 10 def A__ ( self )-> Optional[Any]: '''simple docstring''' __UpperCamelCase = TFOPTModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=__UpperCAmelCase ) def A__ ( self )-> int: '''simple docstring''' self.config_tester.run_common_tests() def A__ ( self )-> List[str]: '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__UpperCAmelCase ) def A__ ( self )-> Any: '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if hasattr(__UpperCAmelCase , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(__UpperCAmelCase , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings __UpperCamelCase = model_class(config=__UpperCAmelCase ) __UpperCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_input_embeddings() ) __UpperCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(__UpperCAmelCase ) __UpperCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_input_embeddings() ) __UpperCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. __UpperCamelCase = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , __UpperCAmelCase ) # check that weights remain the same after resizing __UpperCamelCase = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __UpperCamelCase = False self.assertTrue(__UpperCAmelCase ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , __UpperCAmelCase ) __UpperCamelCase = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __UpperCamelCase = False self.assertTrue(__UpperCAmelCase ) def A_ ( snake_case : Dict ) -> Optional[Any]: '''simple docstring''' return tf.constant(_SCREAMING_SNAKE_CASE , dtype=tf.intaa ) @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" _snake_case = 99 def A__ ( self )-> Optional[int]: '''simple docstring''' __UpperCamelCase = tf.ones((4, 1) , dtype=tf.intaa ) * 2 __UpperCamelCase = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) __UpperCamelCase = input_ids.shape[0] __UpperCamelCase = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" @slow def A__ ( self )-> Optional[Any]: '''simple docstring''' __UpperCamelCase = TFOPTModel.from_pretrained('''facebook/opt-350m''' ) __UpperCamelCase = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) __UpperCamelCase = tf.not_equal(__UpperCAmelCase , model.config.pad_token_id ) with tf.GradientTape(): __UpperCamelCase = model(input_ids=__UpperCAmelCase , attention_mask=__UpperCAmelCase ).last_hidden_state __UpperCamelCase = (1, 11, 512) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCamelCase = tf.constant( [[-0.2_8_7_3, -1.9_2_1_8, -0.3_0_3_3], [-1.2_7_1_0, -0.1_3_3_8, -0.1_9_0_2], [0.4_0_9_5, 0.1_2_1_4, -1.3_1_2_1]] ) self.assertTrue(np.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=4E-3 ) ) __UpperCamelCase = tf.function(__UpperCAmelCase , jit_compile=__UpperCAmelCase ) __UpperCamelCase = xla_generate(__UpperCAmelCase , __UpperCAmelCase )[0] self.assertTrue(np.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=4E-2 ) ) @require_tf @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def A__ ( self )-> List[Any]: '''simple docstring''' super().setUp() __UpperCamelCase = 'facebook/opt-350m' def A__ ( self )-> Tuple: '''simple docstring''' __UpperCamelCase = TFOPTForCausalLM.from_pretrained(self.path_model ) __UpperCamelCase = GPTaTokenizer.from_pretrained(self.path_model ) __UpperCamelCase = [ 'Today is a beautiful day and I want to', 'In the city of', 'Paris is the capital of France and', 'Computers and mobile phones have taken', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False __UpperCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' , padding=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) __UpperCamelCase = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) __UpperCamelCase = tf.constant( [ [1.3_8_5_1, -1_3.8_9_2_3, -1_0.5_2_2_9, -1_0.7_5_3_3, -0.2_3_0_9, -1_0.2_3_8_4, -0.5_3_6_5, -9.0_9_4_7, -5.1_6_7_0], [-4.7_0_7_3, -1_0.6_2_7_6, -3.9_4_1_5, -2_1.5_2_4_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2], [0.6_2_4_7, -3.4_2_2_9, -8.9_1_7_9, -1.4_2_9_7, -1_4.1_6_5_0, 1.4_1_4_6, -9.0_2_1_8, -0.2_7_0_3, -0.2_7_0_3], [6.4_7_8_3, -1.9_9_1_3, -1_0.7_9_2_6, -2.3_3_3_6, 1.5_0_9_2, -0.9_9_7_4, -6.8_2_1_3, 1.3_4_7_7, 1.3_4_7_7], ] ) self.assertTrue(np.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4 ) ) __UpperCamelCase = tf.function(__UpperCAmelCase , jit_compile=__UpperCAmelCase ) __UpperCamelCase = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4 ) ) @require_tf @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" @property def A__ ( self )-> List[Any]: '''simple docstring''' return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def A__ ( self )-> Any: '''simple docstring''' __UpperCamelCase = 'facebook/opt-125m' __UpperCamelCase = [ 'Today is a beautiful day and I want to', 'In the city of New York, the city', 'Paris is the capital of France and the capital', 'Computers and mobile phones have taken over the', ] __UpperCamelCase = [] __UpperCamelCase = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) __UpperCamelCase = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) for prompt in self.prompts: __UpperCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' ).input_ids __UpperCamelCase = model.generate(__UpperCAmelCase , max_length=10 ) __UpperCamelCase = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) predicted_outputs += generated_string self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def A__ ( self )-> str: '''simple docstring''' __UpperCamelCase = 'facebook/opt-350m' __UpperCamelCase = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) __UpperCamelCase = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) __UpperCamelCase = 'left' # use different length sentences to test batching __UpperCamelCase = [ 'Hello, my dog is a little', 'Today, I', ] __UpperCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' , padding=__UpperCAmelCase ) __UpperCamelCase = inputs['input_ids'] __UpperCamelCase = model.generate(input_ids=__UpperCAmelCase , attention_mask=inputs['''attention_mask'''] ) __UpperCamelCase = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids __UpperCamelCase = model.generate(input_ids=__UpperCAmelCase ) __UpperCamelCase = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) __UpperCamelCase = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids __UpperCamelCase = model.generate(input_ids=__UpperCAmelCase , max_length=model.config.max_length - num_paddings ) __UpperCamelCase = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) __UpperCamelCase = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__UpperCAmelCase ) __UpperCamelCase = tokenizer.decode(output_padded[0] , skip_special_tokens=__UpperCAmelCase ) __UpperCamelCase = [ 'Hello, my dog is a little bit of a dork.\nI\'m a little bit', 'Today, I was in the middle of a conversation with a friend about the', ] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , [non_padded_sentence, padded_sentence] ) def A__ ( self )-> Any: '''simple docstring''' __UpperCamelCase = 'facebook/opt-350m' __UpperCamelCase = [ 'Today is a beautiful day and I want to', 'In the city of San Francisco, the city', 'Paris is the capital of France and the capital', 'Computers and mobile phones have taken over the', ] __UpperCamelCase = [] __UpperCamelCase = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) __UpperCamelCase = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) for prompt in self.prompts: __UpperCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' ).input_ids __UpperCamelCase = model.generate(__UpperCAmelCase , max_length=10 ) __UpperCamelCase = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) predicted_outputs += generated_string self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
328
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" lowerCAmelCase__ :str = BertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) lowerCAmelCase__ :int = BertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
293
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase : Any ={"""configuration_glpn""": ["""GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GLPNConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any =["""GLPNFeatureExtractor"""] UpperCAmelCase : Tuple =["""GLPNImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] =[ """GLPN_PRETRAINED_MODEL_ARCHIVE_LIST""", """GLPNForDepthEstimation""", """GLPNLayer""", """GLPNModel""", """GLPNPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys UpperCAmelCase : Dict =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
128
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :List[str] = XGLMTokenizer __magic_name__ :Any = XGLMTokenizerFast __magic_name__ :Dict = True __magic_name__ :Union[str, Any] = True def snake_case ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ :int = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = '<pad>' lowerCAmelCase__ :int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(len(__UpperCAmelCase ) , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase__ :int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase__ :Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) lowerCAmelCase__ :Optional[int] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def snake_case ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) def snake_case ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ :Dict = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :List[str] = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ :Dict = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self.get_rust_tokenizer() lowerCAmelCase__ :Dict = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ :Tuple = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'Hello World!' lowerCAmelCase__ :Tuple = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth' ) # fmt: off lowerCAmelCase__ :List[str] = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = { 'input_ids': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='facebook/xglm-564M' , padding=__UpperCAmelCase , )
293
0
def lowerCAmelCase_ ( __a = 50 ) -> int: """simple docstring""" lowerCamelCase__: str =[[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'{solution() = }')
10
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/config.json", "umberto-commoncrawl-cased-v1": ( "https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json" ), "umberto-wikipedia-uncased-v1": ( "https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json" ), } class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = """camembert""" def __init__( self , lowercase=30_522 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3_072 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=2 , lowercase=0.02 , lowercase=1e-12 , lowercase=1 , lowercase=0 , lowercase=2 , lowercase="absolute" , lowercase=True , lowercase=None , **lowercase , ) -> List[Any]: super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = hidden_act lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps lowerCAmelCase = position_embedding_type lowerCAmelCase = use_cache lowerCAmelCase = classifier_dropout class lowercase ( _UpperCAmelCase ): @property def _snake_case ( self ) -> int: if self.task == "multiple-choice": lowerCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowerCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
46
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(a ) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = {} lowerCAmelCase__ :Tuple = {} lowerCAmelCase__ :Any = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ :Dict = kwargs['points_per_batch'] if "points_per_crop" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: lowerCAmelCase__ :Any = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ :Any = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ :Dict = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ :Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: lowerCAmelCase__ :Optional[int] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: lowerCAmelCase__ :List[Any] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ :int = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: lowerCAmelCase__ :Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ :Optional[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , __UpperCAmelCase , *__UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , *__UpperCAmelCase , num_workers=__UpperCAmelCase , batch_size=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=6_4 , __UpperCAmelCase = 0 , __UpperCAmelCase = 5_1_2 / 1_5_0_0 , __UpperCAmelCase = 3_2 , __UpperCAmelCase = 1 , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = load_image(__UpperCAmelCase ) lowerCAmelCase__ :int = self.image_processor.size['longest_edge'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :int = self.image_processor.generate_crop_boxes( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.image_processor(images=__UpperCAmelCase , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ :Optional[int] = self.get_inference_context() with inference_context(): lowerCAmelCase__ :Any = self._ensure_tensor_on_device(__UpperCAmelCase , device=self.device ) lowerCAmelCase__ :Tuple = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) lowerCAmelCase__ :Optional[int] = image_embeddings lowerCAmelCase__ :List[Any] = grid_points.shape[1] lowerCAmelCase__ :Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ :List[str] = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ :List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=0.88 , __UpperCAmelCase=0.95 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , ): '''simple docstring''' lowerCAmelCase__ :Any = model_inputs.pop('input_boxes' ) lowerCAmelCase__ :Optional[int] = model_inputs.pop('is_last' ) lowerCAmelCase__ :Dict = model_inputs.pop('original_sizes' ).tolist() lowerCAmelCase__ :Dict = model_inputs.pop('reshaped_input_sizes' ).tolist() lowerCAmelCase__ :Optional[int] = self.model(**__UpperCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ :int = model_outputs['pred_masks'] lowerCAmelCase__ :Optional[Any] = self.image_processor.post_process_masks( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , binarize=__UpperCAmelCase ) lowerCAmelCase__ :Any = model_outputs['iou_scores'] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=0.7 , ): '''simple docstring''' lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Optional[Any] = [] lowerCAmelCase__ :int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ :Dict = torch.cat(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = self.image_processor.post_process_for_mask_generation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = defaultdict(__UpperCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = {} if output_rle_mask: lowerCAmelCase__ :str = rle_mask if output_bboxes_mask: lowerCAmelCase__ :Optional[int] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
293
0
"""simple docstring""" 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 lowerCamelCase__ : List[str] = logging.get_logger(__name__) lowerCamelCase__ : Optional[Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} lowerCamelCase__ : int = { '''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''' }, } lowerCamelCase__ : List[Any] = {'''mobilebert-uncased''': 5_12} lowerCamelCase__ : List[str] = {} class _UpperCAmelCase ( __a): __a : str = VOCAB_FILES_NAMES __a : str = PRETRAINED_VOCAB_FILES_MAP __a : List[Any] = PRETRAINED_INIT_CONFIGURATION __a : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : List[str] = MobileBertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ) -> List[Any]: '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) _UpperCAmelCase : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __UpperCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __UpperCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __UpperCAmelCase ) != tokenize_chinese_chars ): _UpperCAmelCase : List[Any] = getattr(__UpperCAmelCase , normalizer_state.pop("""type""" ) ) _UpperCAmelCase : Dict = do_lower_case _UpperCAmelCase : Dict = strip_accents _UpperCAmelCase : Any = tokenize_chinese_chars _UpperCAmelCase : int = normalizer_class(**__UpperCAmelCase ) _UpperCAmelCase : Tuple = do_lower_case def __snake_case ( self , _A , _A=None ) -> Dict: '''simple docstring''' _UpperCAmelCase : Any = [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 __snake_case ( self , _A , _A = None ) -> int: '''simple docstring''' _UpperCAmelCase : Dict = [self.sep_token_id] _UpperCAmelCase : 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 ) * [0] + len(token_ids_a + sep ) * [1] def __snake_case ( self , _A , _A = None ) -> Any: '''simple docstring''' _UpperCAmelCase : int = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
246
"""simple docstring""" from __future__ import annotations __A = 1.6_021e-19 # units = C def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) ->tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
293
0
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
121
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=1_8 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , ): '''simple docstring''' lowerCAmelCase__ :Dict = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :List[Any] = batch_size lowerCAmelCase__ :List[Any] = num_channels lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :int = min_resolution lowerCAmelCase__ :int = max_resolution lowerCAmelCase__ :Dict = do_resize lowerCAmelCase__ :str = size lowerCAmelCase__ :Any = apply_ocr def snake_case ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def snake_case ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCAmelCase , 'apply_ocr' ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowerCAmelCase__ :List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __UpperCAmelCase ) self.assertIsInstance(encoding.boxes , __UpperCAmelCase ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCAmelCase__ :Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase__ :Any = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ :Tuple = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCAmelCase__ :int = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ :Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCAmelCase__ :List[str] = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __UpperCAmelCase ) self.assertListEqual(encoding.boxes , __UpperCAmelCase ) # with apply_OCR = False lowerCAmelCase__ :int = LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = image_processing(__UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
293
0
def __A ( __lowerCamelCase ) -> int: a = [1] a = 0, 0, 0 a = ugly_nums[ia] * 2 a = ugly_nums[ia] * 3 a = ugly_nums[ia] * 5 for _ in range(1 , _SCREAMING_SNAKE_CASE ): a = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ugly_nums.append(_SCREAMING_SNAKE_CASE ) if next_num == next_a: ia += 1 a = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 a = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 a = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F'{ugly_numbers(200) = }')
228
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ReformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ReformerAttention""", """ReformerForMaskedLM""", """ReformerForQuestionAnswering""", """ReformerForSequenceClassification""", """ReformerLayer""", """ReformerModel""", """ReformerModelWithLMHead""", """ReformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
"""simple docstring""" import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A = logging.get_logger(__name__) __A = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} # See all BART models at https://huggingface.co/models?filter=bart __A = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, } __A = { '''facebook/bart-base''': 1024, '''facebook/bart-large''': 1024, '''facebook/bart-large-mnli''': 1024, '''facebook/bart-large-cnn''': 1024, '''facebook/bart-large-xsum''': 1024, '''yjernite/bart_eli5''': 1024, } @lru_cache() def lowercase_ ( ) -> List[Any]: '''simple docstring''' __lowerCamelCase : Dict = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) __lowerCamelCase : Union[str, Any] = bs[:] __lowerCamelCase : Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(_SCREAMING_SNAKE_CASE ) cs.append(2**8 + n ) n += 1 __lowerCamelCase : List[str] = [chr(_SCREAMING_SNAKE_CASE ) for n in cs] return dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def lowercase_ ( _lowerCamelCase: Tuple ) -> Tuple: '''simple docstring''' __lowerCamelCase : Union[str, Any] = set() __lowerCamelCase : str = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCamelCase : Optional[int] = char return pairs class _snake_case ( a__ ): snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["""input_ids""", """attention_mask"""] def __init__( self : Dict , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[int] , UpperCAmelCase : Optional[int]="replace" , UpperCAmelCase : Optional[int]="<s>" , UpperCAmelCase : Optional[int]="</s>" , UpperCAmelCase : Any="</s>" , UpperCAmelCase : Tuple="<s>" , UpperCAmelCase : List[Any]="<unk>" , UpperCAmelCase : Optional[Any]="<pad>" , UpperCAmelCase : Tuple="<mask>" , UpperCAmelCase : Tuple=False , **UpperCAmelCase : Optional[Any] , ): __lowerCamelCase : List[Any] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else bos_token __lowerCamelCase : int = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else eos_token __lowerCamelCase : Optional[Any] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else sep_token __lowerCamelCase : str = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else cls_token __lowerCamelCase : Optional[Any] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else unk_token __lowerCamelCase : Optional[int] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : Union[str, Any] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token super().__init__( errors=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase , **__UpperCAmelCase , ) with open(__UpperCAmelCase , encoding="utf-8" ) as vocab_handle: __lowerCamelCase : int = json.load(__UpperCAmelCase ) __lowerCamelCase : Dict = {v: k for k, v in self.encoder.items()} __lowerCamelCase : List[Any] = errors # how to handle errors in decoding __lowerCamelCase : Optional[int] = bytes_to_unicode() __lowerCamelCase : Tuple = {v: k for k, v in self.byte_encoder.items()} with open(__UpperCAmelCase , encoding="utf-8" ) as merges_handle: __lowerCamelCase : List[Any] = merges_handle.read().split("\n" )[1:-1] __lowerCamelCase : List[Any] = [tuple(merge.split() ) for merge in bpe_merges] __lowerCamelCase : Any = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __lowerCamelCase : Union[str, Any] = {} __lowerCamelCase : List[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __lowerCamelCase : str = re.compile(r"\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def lowerCamelCase__ ( self : Optional[int] ): return len(self.encoder ) def lowerCamelCase__ ( self : Union[str, Any] ): return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase__ ( self : Dict , UpperCAmelCase : Union[str, Any] ): if token in self.cache: return self.cache[token] __lowerCamelCase : List[Any] = tuple(__UpperCAmelCase ) __lowerCamelCase : Dict = get_pairs(__UpperCAmelCase ) if not pairs: return token while True: __lowerCamelCase : str = min(__UpperCAmelCase , key=lambda UpperCAmelCase : self.bpe_ranks.get(__UpperCAmelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __lowerCamelCase : List[str] = bigram __lowerCamelCase : Dict = [] __lowerCamelCase : Optional[Any] = 0 while i < len(__UpperCAmelCase ): try: __lowerCamelCase : List[Any] = word.index(__UpperCAmelCase , __UpperCAmelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowerCamelCase : Dict = 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 __lowerCamelCase : Union[str, Any] = tuple(__UpperCAmelCase ) __lowerCamelCase : Union[str, Any] = new_word if len(__UpperCAmelCase ) == 1: break else: __lowerCamelCase : Dict = get_pairs(__UpperCAmelCase ) __lowerCamelCase : str = ' '.join(__UpperCAmelCase ) __lowerCamelCase : Optional[Any] = word return word def lowerCamelCase__ ( self : List[Any] , UpperCAmelCase : int ): __lowerCamelCase : str = [] for token in re.findall(self.pat , __UpperCAmelCase ): __lowerCamelCase : Dict = ''.join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__UpperCAmelCase ).split(" " ) ) return bpe_tokens def lowerCamelCase__ ( self : Dict , UpperCAmelCase : Optional[Any] ): return self.encoder.get(__UpperCAmelCase , self.encoder.get(self.unk_token ) ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : Optional[int] ): return self.decoder.get(__UpperCAmelCase ) def lowerCamelCase__ ( self : int , UpperCAmelCase : str ): __lowerCamelCase : Optional[int] = ''.join(__UpperCAmelCase ) __lowerCamelCase : Tuple = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def lowerCamelCase__ ( self : Dict , UpperCAmelCase : List[str] , UpperCAmelCase : str = None ): if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase : Optional[int] = os.path.join( __UpperCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __lowerCamelCase : 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" ) __lowerCamelCase : Optional[int] = 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!" ) __lowerCamelCase : Union[str, Any] = token_index writer.write(" ".join(__UpperCAmelCase ) + "\n" ) index += 1 return vocab_file, merge_file def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Tuple = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : List[str] = [self.cls_token_id] __lowerCamelCase : str = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase__ ( self : Tuple , UpperCAmelCase : Dict , UpperCAmelCase : Optional[int] = None , UpperCAmelCase : Optional[int] = False ): 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 lowerCamelCase__ ( self : Optional[Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : Dict = None ): __lowerCamelCase : Optional[Any] = [self.sep_token_id] __lowerCamelCase : Optional[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 lowerCamelCase__ ( self : Tuple , UpperCAmelCase : int , UpperCAmelCase : str=False , **UpperCAmelCase : Any ): __lowerCamelCase : int = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__UpperCAmelCase ) > 0 and not text[0].isspace()): __lowerCamelCase : Any = ' ' + text return (text, kwargs)
135
"""simple docstring""" import math def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be an integer" raise TypeError(_SCREAMING_SNAKE_CASE ) if number < 1: lowerCAmelCase__ :Dict = F"Input value of [number={number}] must be > 0" raise ValueError(_SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowerCAmelCase__ :Union[str, Any] = int(math.log(number // 3 , 2 ) ) + 2 lowerCAmelCase__ :Optional[Any] = [3, 5] lowerCAmelCase__ :Optional[Any] = 2 lowerCAmelCase__ :List[str] = 3 for block in range(1 , _SCREAMING_SNAKE_CASE ): for _ in range(_SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): __A = 0 try: __A = proth(number) except ValueError: print(F'''ValueError: there is no {number}th Proth number''') continue print(F'''The {number}th Proth number: {value}''')
293
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
21
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __A = TypeVar("""KEY""") __A = TypeVar("""VAL""") @dataclass(frozen=a , slots=a ) class _lowerCAmelCase ( Generic[KEY, VAL] ): """simple docstring""" __magic_name__ :KEY __magic_name__ :VAL class _lowerCAmelCase ( _Item ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __bool__( self ): '''simple docstring''' return False __A = _DeletedItem() class _lowerCAmelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , __UpperCAmelCase = 8 , __UpperCAmelCase = 0.75 ): '''simple docstring''' lowerCAmelCase__ :List[str] = initial_block_size lowerCAmelCase__ :list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ :Tuple = capacity_factor lowerCAmelCase__ :str = 0 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return hash(__UpperCAmelCase ) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = self._buckets[ind] if not stored: lowerCAmelCase__ :Dict = _Item(__UpperCAmelCase , __UpperCAmelCase ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ :Optional[Any] = _Item(__UpperCAmelCase , __UpperCAmelCase ) return True else: return False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ :Optional[Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._buckets lowerCAmelCase__ :Tuple = [None] * new_size lowerCAmelCase__ :List[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self._get_bucket_index(__UpperCAmelCase ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ :Tuple = self._get_next_ind(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): if self._try_set(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): break def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(__UpperCAmelCase , __UpperCAmelCase ) def __delitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :int = self._buckets[ind] if item is None: raise KeyError(__UpperCAmelCase ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ :List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' for ind in self._iterate_buckets(__UpperCAmelCase ): lowerCAmelCase__ :str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__UpperCAmelCase ) def __len__( self ): '''simple docstring''' return self._len def __iter__( self ): '''simple docstring''' yield from (item.key for item in self._buckets if item) def __repr__( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = ' ,'.join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
293
0
"""simple docstring""" import os import unicodedata 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 SPIECE_UNDERLINE, logging a_ = logging.get_logger(__name__) a_ = {"""vocab_file""": """spiece.model"""} a_ = { """vocab_file""": { """TsinghuaAI/CPM-Generate""": """https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model""", } } class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , __lowerCamelCase , __lowerCamelCase=False , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase="<s>" , __lowerCamelCase="</s>" , __lowerCamelCase="<unk>" , __lowerCamelCase="<sep>" , __lowerCamelCase="<pad>" , __lowerCamelCase="<cls>" , __lowerCamelCase="<mask>" , __lowerCamelCase=["<eop>", "<eod>"] , __lowerCamelCase = None , **__lowerCamelCase , ): '''simple docstring''' __A : Optional[int] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token __A : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) __A : Tuple = 3 __A : Union[str, Any] = do_lower_case __A : Dict = remove_space __A : List[str] = keep_accents __A : str = vocab_file __A : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) __A : List[Any] = jieba __A : Optional[Any] = str.maketrans(''' \n''' , '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def UpperCamelCase__( self ): '''simple docstring''' return len(self.sp_model ) def UpperCamelCase__( self ): '''simple docstring''' __A : Any = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): '''simple docstring''' __A : int = self.__dict__.copy() __A : Union[str, Any] = None return state def __setstate__( self , __lowerCamelCase ): '''simple docstring''' __A : Union[str, Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __A : Union[str, Any] = {} __A : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' if self.remove_space: __A : List[str] = ' '.join(inputs.strip().split() ) else: __A : Optional[int] = inputs __A : List[str] = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: __A : List[str] = unicodedata.normalize('''NFKD''' , __UpperCAmelCase ) __A : int = ''.join([c for c in outputs if not unicodedata.combining(__UpperCAmelCase )] ) if self.do_lower_case: __A : List[Any] = outputs.lower() return outputs def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' __A : List[Any] = self.preprocess_text(__UpperCAmelCase ) __A : Tuple = self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) __A : int = [] for piece in pieces: if len(__UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): __A : str = self.sp_model.EncodeAsPieces(piece[:-1].replace(__UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __A : Dict = cur_pieces[1:] else: __A : Tuple = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__UpperCAmelCase ) else: new_pieces.append(__UpperCAmelCase ) return new_pieces def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' return self.sp_model.PieceToId(__UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' return self.sp_model.IdToPiece(__UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' __A : List[Any] = ''.join(__UpperCAmelCase ).replace(__UpperCAmelCase , ''' ''' ).strip() return out_string def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase = None ): '''simple docstring''' __A : List[str] = [self.sep_token_id] __A : List[Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False ): '''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 not None: return ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] return ([0] * len(__UpperCAmelCase )) + [1, 1] def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase = None ): '''simple docstring''' __A : Any = [self.sep_token_id] __A : Union[str, Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase = None ): '''simple docstring''' if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __A : 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 ) 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: __A : Dict = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,) def UpperCamelCase__( self , *__lowerCamelCase , **__lowerCamelCase ): '''simple docstring''' __A : List[str] = super()._decode(*__UpperCAmelCase , **__UpperCAmelCase ) __A : int = text.replace(''' ''' , '''''' ).replace('''\u2582''' , ''' ''' ).replace('''\u2583''' , '''\n''' ) return text
179
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __A = logging.getLogger(__name__) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" if os.path.exists(_SCREAMING_SNAKE_CASE ): if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'config.json' ) ) if os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ): os.remove(os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin' ) ) else: os.makedirs(_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :Dict = 2 if unlogit: lowerCAmelCase__ :List[str] = torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = p * torch.log(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 return -plogp.sum(dim=-1 ) def __A (_SCREAMING_SNAKE_CASE ) ->Dict: """simple docstring""" logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(_SCREAMING_SNAKE_CASE ) ) ) ) for row in range(len(_SCREAMING_SNAKE_CASE ) ): if tensor.dtype != torch.long: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:.5f}" for x in tensor[row].cpu().data ) ) else: logger.info(F"layer {row + 1}:\t" + '\t'.join(F"{x:d}" for x in tensor[row].cpu().data ) ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ :Dict = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ :Any = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) lowerCAmelCase__ :Tuple = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) if head_mask is None: lowerCAmelCase__ :Optional[int] = torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(args.device ) head_mask.requires_grad_(requires_grad=_SCREAMING_SNAKE_CASE ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ :List[str] = None lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Any = 0.0 for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ :str = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ :str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :str = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Optional[Any] = entropy(attn.detach() , _SCREAMING_SNAKE_CASE ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_SCREAMING_SNAKE_CASE ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ :Union[str, Any] = 2 lowerCAmelCase__ :Tuple = torch.pow(torch.pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: lowerCAmelCase__ :str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) logger.info('Head ranked by importance scores' ) lowerCAmelCase__ :List[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ :List[Any] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ :int = head_ranks.view_as(_SCREAMING_SNAKE_CASE ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) return attn_entropy, head_importance, total_loss def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _SCREAMING_SNAKE_CASE , original_score * args.masking_threshold ) lowerCAmelCase__ :Optional[int] = torch.ones_like(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ :List[str] = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ :List[str] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ :str = float('Inf' ) lowerCAmelCase__ :List[str] = head_importance.view(-1 ).sort()[1] if len(_SCREAMING_SNAKE_CASE ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads lowerCAmelCase__ :int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ :Dict = new_head_mask.view(-1 ) lowerCAmelCase__ :Any = 0.0 lowerCAmelCase__ :Tuple = new_head_mask.view_as(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = new_head_mask.clone().detach() print_ad_tensor(_SCREAMING_SNAKE_CASE ) # Compute metric and head importance again lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _SCREAMING_SNAKE_CASE , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(_SCREAMING_SNAKE_CASE ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time lowerCAmelCase__ :List[str] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_SCREAMING_SNAKE_CASE ) ) } for k, v in heads_to_prune.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = [ v, ] assert sum(len(_SCREAMING_SNAKE_CASE ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ :int = datetime.now() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = compute_heads_importance( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , compute_entropy=_SCREAMING_SNAKE_CASE , compute_importance=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , actually_pruned=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :int = 1 / loss lowerCAmelCase__ :Tuple = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(_SCREAMING_SNAKE_CASE , args.output_dir ) def __A () ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_SCREAMING_SNAKE_CASE , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_SCREAMING_SNAKE_CASE , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_SCREAMING_SNAKE_CASE , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Batch size.' ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=42 ) parser.add_argument('--local_rank' , type=_SCREAMING_SNAKE_CASE , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_SCREAMING_SNAKE_CASE , default='' , help='Can be used for distant debugging.' ) lowerCAmelCase__ :Any = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_SCREAMING_SNAKE_CASE ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ :List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) lowerCAmelCase__ :Optional[int] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ :Dict = torch.device('cuda' , args.local_rank ) lowerCAmelCase__ :Tuple = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ :int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ :Optional[Any] = nn.parallel.DistributedDataParallel( _SCREAMING_SNAKE_CASE , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_SCREAMING_SNAKE_CASE ) elif args.n_gpu > 1: lowerCAmelCase__ :Union[str, Any] = nn.DataParallel(_SCREAMING_SNAKE_CASE ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) torch.save(_SCREAMING_SNAKE_CASE , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Prepare dataset lowerCAmelCase__ :Optional[int] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ :Union[str, Any] = (torch.from_numpy(_SCREAMING_SNAKE_CASE ),) lowerCAmelCase__ :Optional[int] = TensorDataset(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ :Optional[Any] = mask_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) prune_heads(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" def A_ ( _lowercase ): '''simple docstring''' return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
66
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = 1_0 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = [1, 2, 3, 4] lowerCAmelCase__ :Tuple = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowerCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__UpperCAmelCase , self.block_size , 0 ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = '' lowerCAmelCase__ , lowerCAmelCase__ :Any = process_story(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [] ) self.assertEqual(__UpperCAmelCase , [] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) lowerCAmelCase__ , lowerCAmelCase__ :str = process_story(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = ['It was the best of times.'] self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = torch.tensor([1, 2, 3, 4] ) lowerCAmelCase__ :List[str] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 0 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowerCAmelCase__ :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 2_3 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowerCAmelCase__ :Optional[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__UpperCAmelCase , 1 ).numpy() , expected.numpy() ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 1_0_1 lowerCAmelCase__ :str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowerCAmelCase__ :Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowerCAmelCase__ :List[Any] = compute_token_type_ids(__UpperCAmelCase , __UpperCAmelCase ) np.testing.assert_array_equal(__UpperCAmelCase , __UpperCAmelCase )
293
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1600, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1600, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def A__ ( self )-> str: '''simple docstring''' if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() , encoding='''utf-8''' , check=__UpperCAmelCase , ) assert hasattr(self , '''env''' ) def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Tuple: '''simple docstring''' __UpperCamelCase = { 'enabled': True, 'processes_per_host': 8, } __UpperCamelCase = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __UpperCamelCase = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __UpperCamelCase = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" , instance_count=__UpperCAmelCase , instance_type=self.instance_type , debugger_hook_config=__UpperCAmelCase , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 500, } , metric_definitions=self.env.metric_definitions , distribution=__UpperCAmelCase , py_version='''py36''' , ) def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Tuple: '''simple docstring''' TrainingJobAnalytics(__UpperCAmelCase ).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv" ) @parameterized.expand([(1,)] ) def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Dict: '''simple docstring''' __UpperCamelCase = self.create_estimator(__UpperCAmelCase ) # run training estimator.fit() # result dataframe __UpperCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __UpperCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __UpperCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __UpperCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , __UpperCAmelCase )
328
"""simple docstring""" import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
0
from typing import List from .keymap import KEYMAP, get_character def _lowerCAmelCase (_lowerCAmelCase): def decorator(_lowerCAmelCase): UpperCamelCase_ = getattr(_SCREAMING_SNAKE_CASE , "handle_key" , []) handle += [key] setattr(_SCREAMING_SNAKE_CASE , "handle_key" , _SCREAMING_SNAKE_CASE) return func return decorator def _lowerCAmelCase (*_lowerCAmelCase): def decorator(_lowerCAmelCase): UpperCamelCase_ = getattr(_SCREAMING_SNAKE_CASE , "handle_key" , []) handle += keys setattr(_SCREAMING_SNAKE_CASE , "handle_key" , _SCREAMING_SNAKE_CASE) return func return decorator class _lowercase (a_ ): '''simple docstring''' def __new__( cls , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' UpperCamelCase_ = super().__new__(cls , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if not hasattr(__UpperCAmelCase , "key_handler" ): setattr(__UpperCAmelCase , "key_handler" , {} ) setattr(__UpperCAmelCase , "handle_input" , KeyHandler.handle_input ) for value in attrs.values(): UpperCamelCase_ = getattr(__UpperCAmelCase , "handle_key" , [] ) for key in handled_keys: UpperCamelCase_ = value return new_cls @staticmethod def _lowerCamelCase ( cls ): '''simple docstring''' UpperCamelCase_ = get_character() if char != KEYMAP["undefined"]: UpperCamelCase_ = ord(__UpperCAmelCase ) UpperCamelCase_ = cls.key_handler.get(__UpperCAmelCase ) if handler: UpperCamelCase_ = char return handler(cls ) else: return None def _lowerCAmelCase (cls): return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy())
128
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
0
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": __A = 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.", ) __A = parser.parse_args() __A = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) __A = CLIPImageProcessor() __A = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") __A = 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)
10
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
0