code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase = { "configuration_table_transformer": [ "TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TableTransformerConfig", "TableTransformerOnnxConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TableTransformerForObjectDetection", "TableTransformerModel", "TableTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
308
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) def lowercase__ ( lowerCamelCase : Tuple , lowerCamelCase : Dict=False , lowerCamelCase : Any=False ) -> Union[str, Any]: lowerCAmelCase__ : str = "backbone." if is_semantic else "" lowerCAmelCase__ : str = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"{prefix}blocks.{i}.norm1.weight", F"beit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((F"{prefix}blocks.{i}.norm1.bias", F"beit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (F"{prefix}blocks.{i}.attn.proj.weight", F"beit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append( (F"{prefix}blocks.{i}.attn.proj.bias", F"beit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((F"{prefix}blocks.{i}.norm2.weight", F"beit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((F"{prefix}blocks.{i}.norm2.bias", F"beit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.weight", F"beit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.bias", F"beit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.weight", F"beit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.bias", F"beit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ (F"{prefix}cls_token", "beit.embeddings.cls_token"), (F"{prefix}patch_embed.proj.weight", "beit.embeddings.patch_embeddings.projection.weight"), (F"{prefix}patch_embed.proj.bias", "beit.embeddings.patch_embeddings.projection.bias"), (F"{prefix}pos_embed", "beit.embeddings.position_embeddings"), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ("mask_token", "beit.embeddings.mask_token"), ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ] ) else: # layernorm + classification head rename_keys.extend( [ ("fc_norm.weight", "beit.pooler.layernorm.weight"), ("fc_norm.bias", "beit.pooler.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def lowercase__ ( lowerCamelCase : int , lowerCamelCase : Tuple , lowerCamelCase : int=False , lowerCamelCase : Union[str, Any]=False ) -> List[str]: for i in range(config.num_hidden_layers ): lowerCAmelCase__ : Optional[int] = "backbone." if is_semantic else "" # queries, keys and values lowerCAmelCase__ : Any = state_dict.pop(F"{prefix}blocks.{i}.attn.qkv.weight" ) lowerCAmelCase__ : List[Any] = state_dict.pop(F"{prefix}blocks.{i}.attn.q_bias" ) lowerCAmelCase__ : Dict = state_dict.pop(F"{prefix}blocks.{i}.attn.v_bias" ) lowerCAmelCase__ : Tuple = in_proj_weight[ : config.hidden_size, : ] lowerCAmelCase__ : Optional[Any] = q_bias lowerCAmelCase__ : Optional[int] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCAmelCase__ : Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] lowerCAmelCase__ : List[Any] = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained lowerCAmelCase__ : Optional[Any] = state_dict.pop(F"{prefix}blocks.{i}.gamma_1" ) lowerCAmelCase__ : Optional[Any] = state_dict.pop(F"{prefix}blocks.{i}.gamma_2" ) lowerCAmelCase__ : Union[str, Any] = gamma_a lowerCAmelCase__ : Optional[Any] = gamma_a def lowercase__ ( lowerCamelCase : int , lowerCamelCase : Union[str, Any] , lowerCamelCase : Tuple ) -> List[Any]: lowerCAmelCase__ : Dict = dct.pop(lowerCamelCase ) lowerCAmelCase__ : Union[str, Any] = val def lowercase__ ( ) -> Any: lowerCAmelCase__ : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ : Tuple = Image.open(requests.get(lowerCamelCase , stream=lowerCamelCase ).raw ) return im @torch.no_grad() def lowercase__ ( lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : List[str]=False ) -> int: lowerCAmelCase__ : Optional[int] = False if "rvlcdip" in checkpoint_url else True lowerCAmelCase__ : Any = BeitConfig(use_absolute_position_embeddings=lowerCamelCase , use_mask_token=lowerCamelCase ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: lowerCAmelCase__ : Optional[Any] = 1_0_2_4 lowerCAmelCase__ : Any = 4_0_9_6 lowerCAmelCase__ : int = 2_4 lowerCAmelCase__ : Tuple = 1_6 # labels if "rvlcdip" in checkpoint_url: lowerCAmelCase__ : Optional[Any] = 1_6 lowerCAmelCase__ : str = "huggingface/label-files" lowerCAmelCase__ : List[str] = "rvlcdip-id2label.json" lowerCAmelCase__ : Tuple = json.load(open(hf_hub_download(lowerCamelCase , lowerCamelCase , repo_type="dataset" ) , "r" ) ) lowerCAmelCase__ : Tuple = {int(lowerCamelCase ): v for k, v in idalabel.items()} lowerCAmelCase__ : Optional[Any] = idalabel lowerCAmelCase__ : Any = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys lowerCAmelCase__ : int = torch.hub.load_state_dict_from_url(lowerCamelCase , map_location="cpu" )["model"] lowerCAmelCase__ : Union[str, Any] = create_rename_keys(lowerCamelCase , has_lm_head=lowerCamelCase ) for src, dest in rename_keys: rename_key(lowerCamelCase , lowerCamelCase , lowerCamelCase ) read_in_q_k_v(lowerCamelCase , lowerCamelCase , has_lm_head=lowerCamelCase ) # load HuggingFace model lowerCAmelCase__ : Union[str, Any] = BeitForMaskedImageModeling(lowerCamelCase ) if has_lm_head else BeitForImageClassification(lowerCamelCase ) model.eval() model.load_state_dict(lowerCamelCase ) # Check outputs on an image lowerCAmelCase__ : Dict = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=lowerCamelCase ) lowerCAmelCase__ : str = prepare_img() lowerCAmelCase__ : List[str] = image_processor(images=lowerCamelCase , return_tensors="pt" ) lowerCAmelCase__ : Any = encoding["pixel_values"] lowerCAmelCase__ : Optional[Any] = model(lowerCamelCase ) lowerCAmelCase__ : Union[str, Any] = outputs.logits # verify logits lowerCAmelCase__ : str = [1, 1_6] if "rvlcdip" in checkpoint_url else [1, 1_9_6, 8_1_9_2] assert logits.shape == torch.Size(lowerCamelCase ), "Shape of logits not as expected" Path(lowerCamelCase ).mkdir(exist_ok=lowerCamelCase ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(lowerCamelCase ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(lowerCamelCase ) if push_to_hub: if has_lm_head: lowerCAmelCase__ : List[Any] = "dit-base" if "base" in checkpoint_url else "dit-large" else: lowerCAmelCase__ : Tuple = "dit-base-finetuned-rvlcdip" if "dit-b" in checkpoint_url else "dit-large-finetuned-rvlcdip" image_processor.push_to_hub( repo_path_or_name=Path(lowerCamelCase , lowerCamelCase ) , organization="nielsr" , commit_message="Add image processor" , use_temp_dir=lowerCamelCase , ) model.push_to_hub( repo_path_or_name=Path(lowerCamelCase , lowerCamelCase ) , organization="nielsr" , commit_message="Add model" , use_temp_dir=lowerCamelCase , ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth", type=str, help="URL to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", ) __UpperCAmelCase = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
308
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,unittest.TestCase ): '''simple docstring''' UpperCamelCase__ =AltDiffusionPipeline UpperCamelCase__ =TEXT_TO_IMAGE_PARAMS UpperCamelCase__ =TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase__ =TEXT_TO_IMAGE_IMAGE_PARAMS UpperCamelCase__ =TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase__ ( self : List[Any] ) -> Any: torch.manual_seed(0 ) __magic_name__ : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) __magic_name__ : Optional[Any] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=__lowerCAmelCase , set_alpha_to_one=__lowerCAmelCase , ) torch.manual_seed(0 ) __magic_name__ : Tuple = 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 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) __magic_name__ : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5002 , ) __magic_name__ : Dict = CLIPTextModel(__lowerCAmelCase ) __magic_name__ : Optional[int] = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) __magic_name__ : Tuple = 77 __magic_name__ : Tuple = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCAmelCase__ ( self : List[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Any=0 ) -> Dict: if str(__lowerCAmelCase ).startswith('''mps''' ): __magic_name__ : List[str] = torch.manual_seed(__lowerCAmelCase ) else: __magic_name__ : str = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase ) __magic_name__ : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase__ ( self : int ) -> Any: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: __magic_name__ : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator __magic_name__ : List[str] = self.get_dummy_components() torch.manual_seed(0 ) __magic_name__ : Optional[int] = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5002 , ) # TODO: remove after fixing the non-deterministic text encoder __magic_name__ : Dict = RobertaSeriesModelWithTransformation(__lowerCAmelCase ) __magic_name__ : Any = text_encoder __magic_name__ : int = AltDiffusionPipeline(**__lowerCAmelCase ) __magic_name__ : Optional[Any] = alt_pipe.to(__lowerCAmelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) __magic_name__ : int = self.get_dummy_inputs(__lowerCAmelCase ) __magic_name__ : List[Any] = '''A photo of an astronaut''' __magic_name__ : List[Any] = alt_pipe(**__lowerCAmelCase ) __magic_name__ : Tuple = output.images __magic_name__ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __magic_name__ : Optional[int] = np.array( [0.5_7_4_8_1_6_2, 0.6_0_4_4_7_1_4_5, 0.4_8_8_2_1_2_1_7, 0.5_0_1_0_0_6_3_6, 0.5_4_3_1_1_8_5, 0.4_5_7_6_3_6_8_3, 0.4_9_6_5_7_6_9_6, 0.4_8_1_3_2_7_3_3, 0.4_7_5_7_3_0_9_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Optional[int] ) -> str: __magic_name__ : Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __magic_name__ : List[Any] = self.get_dummy_components() __magic_name__ : str = PNDMScheduler(skip_prk_steps=__lowerCAmelCase ) torch.manual_seed(0 ) __magic_name__ : List[Any] = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5002 , ) # TODO: remove after fixing the non-deterministic text encoder __magic_name__ : Any = RobertaSeriesModelWithTransformation(__lowerCAmelCase ) __magic_name__ : Any = text_encoder __magic_name__ : int = AltDiffusionPipeline(**__lowerCAmelCase ) __magic_name__ : int = alt_pipe.to(__lowerCAmelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) __magic_name__ : str = self.get_dummy_inputs(__lowerCAmelCase ) __magic_name__ : Optional[int] = alt_pipe(**__lowerCAmelCase ) __magic_name__ : Union[str, Any] = output.images __magic_name__ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __magic_name__ : List[Any] = np.array( [0.5_1_6_0_5_0_9_3, 0.5_7_0_7_2_4_1, 0.4_7_3_6_5_5_0_7, 0.5_0_5_7_8_8_8_6, 0.5_6_3_3_8_7_7, 0.4_6_4_2_5_0_3, 0.5_1_8_2_0_8_1, 0.4_8_7_6_3_4_8_4, 0.4_9_0_8_4_2_3_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase__ ( self : str ) -> Dict: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : str ) -> Tuple: __magic_name__ : Union[str, Any] = AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion''' , safety_checker=__lowerCAmelCase ) __magic_name__ : int = alt_pipe.to(__lowerCAmelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) __magic_name__ : Any = '''A painting of a squirrel eating a burger''' __magic_name__ : Optional[int] = torch.manual_seed(0 ) __magic_name__ : List[Any] = alt_pipe([prompt] , generator=__lowerCAmelCase , guidance_scale=6.0 , num_inference_steps=20 , output_type='''np''' ) __magic_name__ : List[Any] = output.images __magic_name__ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __magic_name__ : Tuple = np.array([0.1_0_1_0, 0.0_8_0_0, 0.0_7_9_4, 0.0_8_8_5, 0.0_8_4_3, 0.0_7_6_2, 0.0_7_6_9, 0.0_7_2_9, 0.0_5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: __magic_name__ : Dict = DDIMScheduler.from_pretrained('''BAAI/AltDiffusion''' , subfolder='''scheduler''' ) __magic_name__ : List[Any] = AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion''' , scheduler=__lowerCAmelCase , safety_checker=__lowerCAmelCase ) __magic_name__ : List[Any] = alt_pipe.to(__lowerCAmelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) __magic_name__ : Dict = '''A painting of a squirrel eating a burger''' __magic_name__ : Union[str, Any] = torch.manual_seed(0 ) __magic_name__ : Optional[Any] = alt_pipe([prompt] , generator=__lowerCAmelCase , num_inference_steps=2 , output_type='''numpy''' ) __magic_name__ : Tuple = output.images __magic_name__ : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __magic_name__ : Any = np.array([0.4_0_1_9, 0.4_0_5_2, 0.3_8_1_0, 0.4_1_1_9, 0.3_9_1_6, 0.3_9_8_2, 0.4_6_5_1, 0.4_1_9_5, 0.5_3_2_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
707
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 lowercase__ ( __A: str ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowercase__ ( __A: str ): '''simple docstring''' __magic_name__ : List[str] = np.max(_outputs ,axis=-1 ,keepdims=__A ) __magic_name__ : int = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 ,keepdims=__A ) class lowerCamelCase ( _lowerCamelCase ): '''simple docstring''' UpperCamelCase__ ='''sigmoid''' UpperCamelCase__ ='''softmax''' UpperCamelCase__ ='''none''' @add_end_docstrings( _lowerCamelCase ,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 ( _lowerCamelCase ): '''simple docstring''' UpperCamelCase__ =False UpperCamelCase__ =ClassificationFunction.NONE def __init__( self : Tuple , **lowerCamelCase_ : Tuple ) -> List[Any]: super().__init__(**lowerCamelCase_ ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def UpperCAmelCase__ ( self : Optional[int] , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : Dict=None , lowerCamelCase_ : Optional[int]="" , **lowerCamelCase_ : int ) -> str: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" __magic_name__ : Dict = tokenizer_kwargs __magic_name__ : Dict = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: __magic_name__ : List[str] = self.model.config.return_all_scores if isinstance(lowerCamelCase_ , lowerCamelCase_ ) or top_k is None: __magic_name__ : Dict = top_k __magic_name__ : List[Any] = 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`.''' , lowerCamelCase_ , ) if return_all_scores: __magic_name__ : str = None else: __magic_name__ : int = 1 if isinstance(lowerCamelCase_ , lowerCamelCase_ ): __magic_name__ : str = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: __magic_name__ : List[str] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : Optional[Any] , *lowerCamelCase_ : Union[str, Any] , **lowerCamelCase_ : Union[str, Any] ) -> Optional[int]: __magic_name__ : Optional[int] = super().__call__(*lowerCamelCase_ , **lowerCamelCase_ ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. __magic_name__ : int = '''top_k''' not in kwargs if isinstance(args[0] , lowerCamelCase_ ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def UpperCAmelCase__ ( self : Optional[Any] , lowerCamelCase_ : Any , **lowerCamelCase_ : int ) -> Dict[str, GenericTensor]: __magic_name__ : Union[str, Any] = self.framework if isinstance(lowerCamelCase_ , lowerCamelCase_ ): return self.tokenizer(**lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) elif isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(lowerCamelCase_ ) == 1 and isinstance(inputs[0] , lowerCamelCase_ ) 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=lowerCamelCase_ , **lowerCamelCase_ ) elif isinstance(lowerCamelCase_ , lowerCamelCase_ ): # 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(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) def UpperCAmelCase__ ( self : str , lowerCamelCase_ : Dict ) -> Union[str, Any]: return self.model(**lowerCamelCase_ ) def UpperCAmelCase__ ( self : Dict , lowerCamelCase_ : Dict , lowerCamelCase_ : Dict=None , lowerCamelCase_ : List[str]=1 , lowerCamelCase_ : Any=True ) -> int: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: __magic_name__ : Union[str, Any] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: __magic_name__ : str = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: __magic_name__ : Dict = self.model.config.function_to_apply else: __magic_name__ : Optional[Any] = ClassificationFunction.NONE __magic_name__ : Any = model_outputs['''logits'''][0] __magic_name__ : Optional[int] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: __magic_name__ : List[str] = sigmoid(lowerCamelCase_ ) elif function_to_apply == ClassificationFunction.SOFTMAX: __magic_name__ : Optional[int] = softmax(lowerCamelCase_ ) elif function_to_apply == ClassificationFunction.NONE: __magic_name__ : Optional[int] = 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()} __magic_name__ : Union[str, Any] = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(lowerCamelCase_ ) ] if not _legacy: dict_scores.sort(key=lambda lowerCamelCase_ : x["score"] , reverse=lowerCamelCase_ ) if top_k is not None: __magic_name__ : Dict = dict_scores[:top_k] return dict_scores
501
0
import warnings from ..trainer import Trainer from ..utils import logging __lowerCamelCase = logging.get_logger(__name__) class _snake_case ( __lowerCamelCase ): """simple docstring""" def __init__( self , a=None , **a ) -> Dict: """simple docstring""" warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , a__ , ) super().__init__(args=a__ , **a__ )
317
'''simple docstring''' from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase__ ( __lowerCamelCase ): """simple docstring""" UpperCamelCase__ = '''EncodecFeatureExtractor''' UpperCamelCase__ = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : int ,a__ : int ,a__ : Optional[Any] ): super().__init__(a__ ,a__ ) a__ = self.feature_extractor a__ = False def lowerCAmelCase_ ( self : Optional[int] ,a__ : List[Any]=None ,a__ : str=None ,a__ : int=True ): return self.tokenizer.get_decoder_prompt_ids(task=a__ ,language=a__ ,no_timestamps=a__ ) def __call__( self : Any ,*a__ : Union[str, Any] ,**a__ : Any ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a__ ,**a__ ) a__ = kwargs.pop("audio" ,a__ ) a__ = kwargs.pop("sampling_rate" ,a__ ) a__ = kwargs.pop("text" ,a__ ) if len(a__ ) > 0: a__ = args[0] a__ = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if text is not None: a__ = self.tokenizer(a__ ,**a__ ) if audio is not None: a__ = self.feature_extractor(a__ ,*a__ ,sampling_rate=a__ ,**a__ ) if audio is None: return inputs elif text is None: return audio_inputs else: a__ = audio_inputs["input_values"] if "padding_mask" in audio_inputs: a__ = audio_inputs["padding_mask"] return inputs def lowerCAmelCase_ ( self : str ,*a__ : Union[str, Any] ,**a__ : Optional[Any] ): a__ = kwargs.pop("audio" ,a__ ) a__ = kwargs.pop("padding_mask" ,a__ ) if len(a__ ) > 0: a__ = args[0] a__ = args[1:] if audio_values is not None: return self._decode_audio(a__ ,padding_mask=a__ ) else: return self.tokenizer.batch_decode(*a__ ,**a__ ) def lowerCAmelCase_ ( self : Any ,*a__ : List[str] ,**a__ : Tuple ): return self.tokenizer.decode(*a__ ,**a__ ) def lowerCAmelCase_ ( self : Optional[int] ,a__ : Optional[Any] ,a__ : Optional = None ): a__ = to_numpy(a__ ) a__ , a__ , a__ = audio_values.shape if padding_mask is None: return list(a__ ) a__ = to_numpy(a__ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) a__ = seq_len - padding_mask.shape[-1] a__ = 1 - self.feature_extractor.padding_value a__ = np.pad(a__ ,((0, 0), (0, difference)) ,"constant" ,constant_values=a__ ) a__ = audio_values.tolist() for i in range(a__ ): a__ = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] a__ = sliced_audio.reshape(a__ ,-1 ) return audio_values
331
0
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCamelCase_ ( _lowercase , _lowercase , _lowercase = 10**-10 ) -> float: __A : Any = a while True: __A : List[Any] = Decimal(_lowercase ) - ( Decimal(eval(_lowercase ) ) / Decimal(eval(str(diff(_lowercase ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(_lowercase ) ) < precision: # noqa: S307 return float(_lowercase ) # 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)}''')
387
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class _a ( lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Union[str, Any] = """gpt_neox""" def __init__( self , __UpperCAmelCase=50_432 , __UpperCAmelCase=6_144 , __UpperCAmelCase=44 , __UpperCAmelCase=64 , __UpperCAmelCase=24_576 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.25 , __UpperCAmelCase=10_000 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase=2_048 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1e-5 , __UpperCAmelCase=True , __UpperCAmelCase=0 , __UpperCAmelCase=2 , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ): super().__init__(bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) __A : Optional[int] = vocab_size __A : List[Any] = max_position_embeddings __A : Any = hidden_size __A : str = num_hidden_layers __A : List[str] = num_attention_heads __A : Dict = intermediate_size __A : List[Any] = hidden_act __A : Tuple = rotary_pct __A : Optional[int] = rotary_emb_base __A : int = attention_dropout __A : Optional[int] = hidden_dropout __A : List[Any] = classifier_dropout __A : Optional[Any] = initializer_range __A : Optional[int] = layer_norm_eps __A : str = use_cache __A : Optional[int] = tie_word_embeddings __A : Any = use_parallel_residual __A : List[Any] = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( "The hidden size is not divisble by the number of attention heads! Make sure to update them!" ) def __UpperCAmelCase( self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __UpperCAmelCase ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " F"got {self.rope_scaling}" ) __A : Dict = self.rope_scaling.get("type" , __UpperCAmelCase ) __A : Dict = self.rope_scaling.get("factor" , __UpperCAmelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(__UpperCAmelCase , __UpperCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
387
1
"""simple docstring""" import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) a : Tuple = logging.getLogger(__name__) @dataclass(frozen=_lowercase ) class lowercase: __snake_case: Optional[Any] = 42 __snake_case: List[str] = 42 __snake_case: Union[str, Any] = None __snake_case: Tuple = None __snake_case: Tuple = None @dataclass(frozen=_lowercase ) class lowercase: __snake_case: Tuple = 42 __snake_case: str = None __snake_case: Optional[Any] = None __snake_case: Optional[Any] = None __snake_case: List[Any] = None if is_torch_available(): import torch from torch.utils.data import Dataset class lowercase(_lowercase ): __snake_case: Any = 42 def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE = False , ) -> Dict: """simple docstring""" a__ = hans_processors[task]() a__ = os.path.join( SCREAMING_SNAKE_CASE__ , 'cached_{}_{}_{}_{}'.format( 'dev' if evaluate else 'train' , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , ) , ) a__ = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) a__ = label_list[2], label_list[1] a__ = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. a__ = cached_features_file + '.lock' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'Loading features from cached file {cached_features_file}' ) a__ = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'Creating features from dataset file at {data_dir}' ) a__ = ( processor.get_dev_examples(SCREAMING_SNAKE_CASE__ ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE__ ) ) logger.info('Training examples: %s' , len(SCREAMING_SNAKE_CASE__ ) ) a__ = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) logger.info('Saving features into cached file %s' , SCREAMING_SNAKE_CASE__ ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.features ) def __getitem__( self , __SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.features[i] def lowercase__ ( self ) -> Optional[int]: """simple docstring""" return self.label_list if is_tf_available(): import tensorflow as tf class lowercase: __snake_case: str = 42 def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 1_2_8 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE = False , ) -> Optional[Any]: """simple docstring""" a__ = hans_processors[task]() a__ = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) a__ = label_list[2], label_list[1] a__ = label_list a__ = processor.get_dev_examples(SCREAMING_SNAKE_CASE__ ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE__ ) a__ = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc='convert examples to features' ): if ex_index % 1_0_0_0_0 == 0: logger.info('Writing example %d of %d' % (ex_index, len(SCREAMING_SNAKE_CASE__ )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) a__ = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ( { 'example_id': tf.intaa, 'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa, }, tf.intaa, ) , ( { 'example_id': tf.TensorShape([] ), 'input_ids': tf.TensorShape([None, None] ), 'attention_mask': tf.TensorShape([None, None] ), 'token_type_ids': tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def lowercase__ ( self ) -> Any: """simple docstring""" return self.dataset def __len__( self ) -> str: """simple docstring""" return len(self.features ) def __getitem__( self , __SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return self.features[i] def lowercase__ ( self ) -> Union[str, Any]: """simple docstring""" return self.label_list class lowercase(_lowercase ): def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE__ , 'heuristics_train_set.txt' ) ) , 'train' ) def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE__ , 'heuristics_evaluation_set.txt' ) ) , 'dev' ) def lowercase__ ( self ) -> List[str]: """simple docstring""" return ["contradiction", "entailment", "neutral"] def lowercase__ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" a__ = [] for i, line in enumerate(SCREAMING_SNAKE_CASE__ ): if i == 0: continue a__ = '%s-%s' % (set_type, line[0]) a__ = line[5] a__ = line[6] a__ = line[7][2:] if line[7].startswith('ex' ) else line[7] a__ = line[0] examples.append(InputExample(guid=SCREAMING_SNAKE_CASE__ , text_a=SCREAMING_SNAKE_CASE__ , text_b=SCREAMING_SNAKE_CASE__ , label=SCREAMING_SNAKE_CASE__ , pairID=SCREAMING_SNAKE_CASE__ ) ) return examples def __magic_name__ ( UpperCamelCase : List[InputExample] , UpperCamelCase : List[str] , UpperCamelCase : int , UpperCamelCase : PreTrainedTokenizer , ) -> Dict: a__ = {label: i for i, label in enumerate(__A )} a__ = [] for ex_index, example in tqdm.tqdm(enumerate(__A ) , desc='convert examples to features' ): if ex_index % 10000 == 0: logger.info('Writing example %d' % (ex_index) ) a__ = tokenizer( example.text_a , example.text_b , add_special_tokens=__A , max_length=__A , padding='max_length' , truncation=__A , return_overflowing_tokens=__A , ) a__ = label_map[example.label] if example.label in label_map else 0 a__ = int(example.pairID ) features.append(InputFeatures(**__A , label=__A , pairID=__A ) ) for i, example in enumerate(examples[:5] ): logger.info('*** Example ***' ) logger.info(f'guid: {example}' ) logger.info(f'features: {features[i]}' ) return features a : Any = { 'hans': 3, } a : Any = { 'hans': HansProcessor, }
273
'''simple docstring''' from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __UpperCAmelCase = TypeVar("KEY") __UpperCAmelCase = TypeVar("VAL") @dataclass(frozen=snake_case , slots=snake_case ) class SCREAMING_SNAKE_CASE ( Generic[KEY, VAL] ): '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = 42 class SCREAMING_SNAKE_CASE ( _Item ): '''simple docstring''' def __init__( self ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __bool__( self ): '''simple docstring''' return False __UpperCAmelCase = _DeletedItem() class SCREAMING_SNAKE_CASE ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = 8 , SCREAMING_SNAKE_CASE__ = 0.75 ): '''simple docstring''' snake_case: str = initial_block_size snake_case: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 snake_case: List[Any] = capacity_factor snake_case: int = 0 def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return (ind + 1) % len(self._buckets ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Tuple = self._buckets[ind] if not stored: snake_case: Optional[Any] = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self._len += 1 return True elif stored.key == key: snake_case: List[str] = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return True else: return False def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = len(self._buckets ) * self._capacity_factor return len(self ) >= int(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' if len(self._buckets ) <= self._initial_block_size: return False snake_case: Union[str, Any] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = self._buckets snake_case: Optional[Any] = [None] * new_size snake_case: Optional[Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def _UpperCamelCase ( self ): '''simple docstring''' self._resize(len(self._buckets ) * 2 ) def _UpperCamelCase ( self ): '''simple docstring''' self._resize(len(self._buckets ) // 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Tuple = self._get_bucket_index(SCREAMING_SNAKE_CASE__ ) for _ in range(len(self._buckets ) ): yield ind snake_case: int = self._get_next_ind(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): break def __setitem__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self._is_full(): self._size_up() self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __delitem__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): snake_case: List[str] = self._buckets[ind] if item is None: raise KeyError(SCREAMING_SNAKE_CASE__ ) if item is _deleted: continue if item.key == key: snake_case: str = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): snake_case: Union[str, Any] = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(SCREAMING_SNAKE_CASE__ ) 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''' snake_case: Union[str, Any] = ' ,'.join( F"""{item.key}: {item.val}""" for item in self._buckets if item ) return F"""HashMap({val_string})"""
329
0
"""simple docstring""" import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): UpperCAmelCase__ =get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase__ =12_8022 UpperCAmelCase__ =12_8028 @require_sentencepiece class lowerCamelCase__ ( _a , unittest.TestCase ): a : Dict = MaMaaaTokenizer a : Optional[int] = False a : str = False a : Any = True def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().setUp() __lowercase = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] __lowercase = dict(zip(A_ , range(len(A_ ) ) ) ) __lowercase = Path(self.tmpdirname ) save_json(A_ , save_dir / VOCAB_FILES_NAMES["""vocab_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(A_ , save_dir / VOCAB_FILES_NAMES["""spm_file"""] ) __lowercase = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , **A_ : List[Any] ): '''simple docstring''' return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , A_ : Optional[int] ): '''simple docstring''' return ( "This is a test", "This is a test", ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' __lowercase = """</s>""" __lowercase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) , A_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) , A_ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' __lowercase = self.get_tokenizer() __lowercase = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<s>""" ) self.assertEqual(len(A_ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip("""Skip this test while all models are still to be uploaded.""" ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' __lowercase = self.get_tokenizer() __lowercase = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(A_ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A_ ) , [2, 3, 4, 5, 6] , ) __lowercase = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(A_ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) __lowercase = tokenizer.convert_tokens_to_string(A_ ) self.assertEqual(A_ , """This is a test""" ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' __lowercase = {"""input_ids""": [[1_2_8_0_2_2, 1_1_0_1_0_8, 3_9_7, 1_1, 3_8_2_7_2, 2_2_4_7, 1_2_4_8_1_1, 2_8_5, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 3_9_5_3_4, 4_4_2_8, 3_9_7, 1_0_1_9, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 4_1_3_3_7, 1_6_7_8_6, 2_4_1, 7, 2_0_2_1_4, 1_7, 1_2_5_6_9_0, 1_0_3_9_8, 7, 4_4_3_7_8, 5_8_0_6_9, 6_8_3_4_2, 7_7_9_8, 7_3_4_3, 1_1, 2_9_9, 3_3_3_1_0, 4, 1_5_8, 3_7_3_5_0, 9_4_0_7_7, 4_5_6_9, 2_9_9, 3_3_3_1_0, 9_0, 4, 5_2_8_4_0, 2_9_0, 4, 3_1_2_7_0, 1_1_2, 2_9_9, 6_8_2, 4, 5_2_8_4_0, 3_9_9_5_3, 1_4_0_7_9, 1_9_3, 5_2_5_1_9, 9_0_8_9_4, 1_7_8_9_4, 1_2_0_6_9_7, 1_1, 4_0_4_4_5, 5_5_1, 1_7, 1_0_1_9, 5_2_5_1_9, 9_0_8_9_4, 1_7_7_5_6, 9_6_3, 1_1, 4_0_4_4_5, 4_8_0, 1_7, 9_7_9_2, 1_1_2_0, 5_1_7_3, 1_3_9_3, 6_2_4_0, 1_6_7_8_6, 2_4_1, 1_2_0_9_9_6, 2_8, 1_2_4_5, 1_3_9_3, 1_1_8_2_4_0, 1_1_1_2_3, 1_0_1_9, 9_3_6_1_2, 2_6_9_1, 1_0_6_1_8, 9_8_0_5_8, 1_2_0_4_0_9, 1_9_2_8, 2_7_9, 4, 4_0_6_8_3, 3_6_7, 1_7_8, 2_0_7, 1_0_1_9, 1_0_3, 1_0_3_1_2_1, 5_0_6, 6_5_2_9_6, 5, 2], [1_2_8_0_2_2, 2_1_2_1_7, 3_6_7, 1_1_7, 1_2_5_4_5_0, 1_2_8, 7_1_9, 7, 7_3_0_8, 4_0, 9_3_6_1_2, 1_2_6_6_9, 1_1_1_6, 1_6_7_0_4, 7_1, 1_7_7_8_5, 3_6_9_9, 1_5_5_9_2, 3_5, 1_4_4, 9_5_8_4, 2_4_1, 1_1_9_4_3, 7_1_3, 9_5_0, 7_9_9, 2_2_4_7, 8_8_4_2_7, 1_5_0, 1_4_9, 1_1_8_8_1_3, 1_2_0_7_0_6, 1_0_1_9, 1_0_6_9_0_6, 8_1_5_1_8, 2_8, 1_2_2_4, 2_2_7_9_9, 3_9_7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1_2_8_0_2_2, 1_6_5_8, 1_2_3_3_1_1, 5_1_5_5, 5_5_7_8, 4_7_2_2, 2_7_9, 1_4_9_4_7, 2_3_6_6, 1_1_2_0, 1_1_9_7, 1_4, 1_3_4_8, 9_2_3_2, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A_ , model_name="""facebook/m2m100_418M""" , revision="""c168bae485c864188cf9aa0e4108b0b6934dc91e""" , ) @require_torch @require_sentencepiece @require_tokenizers class lowerCamelCase__ ( unittest.TestCase ): a : Optional[int] = """facebook/m2m100_418M""" a : str = [ """In my opinion, there are two levels of response from the French government.""", """NSA Affair Emphasizes Complete Lack of Debate on Intelligence""", ] a : int = [ """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""", """L'affaire NSA souligne l'absence totale de débat sur le renseignement""", ] # fmt: off a : Optional[int] = [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2] @classmethod def SCREAMING_SNAKE_CASE_ ( cls : str ): '''simple docstring''' __lowercase = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en""" , tgt_lang="""fr""" ) __lowercase = 1 return cls def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' self.assertEqual(self.tokenizer.get_lang_id("""ar""" ) , 1_2_8_0_0_6 ) self.assertEqual(self.tokenizer.get_lang_id("""en""" ) , 1_2_8_0_2_2 ) self.assertEqual(self.tokenizer.get_lang_id("""ro""" ) , 1_2_8_0_7_6 ) self.assertEqual(self.tokenizer.get_lang_id("""mr""" ) , 1_2_8_0_6_3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' __lowercase = self.tokenizer.get_vocab() self.assertEqual(len(A_ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab["""<unk>"""] , 3 ) self.assertIn(self.tokenizer.get_lang_token("""en""" ) , A_ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' __lowercase = """en""" __lowercase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , A_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' self.assertIn(A_ , self.tokenizer.all_special_ids ) # fmt: off __lowercase = [FR_CODE, 5_3_6_4, 8_2, 8_6_4_2, 4, 2_9_4, 4_7, 8, 1_4_0_2_8, 1_3_6, 3_2_8_6, 9_7_0_6, 6, 9_0_7_9_7, 6, 1_4_4_0_1_2, 1_6_2, 8_8_1_2_8, 3_0_0_6_1, 5, 2] # fmt: on __lowercase = self.tokenizer.decode(A_ , skip_special_tokens=A_ ) __lowercase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=A_ ) self.assertEqual(A_ , A_ ) self.assertNotIn(self.tokenizer.eos_token , A_ ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' __lowercase = tempfile.mkdtemp() __lowercase = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(A_ ) __lowercase = MaMaaaTokenizer.from_pretrained(A_ ) self.assertDictEqual(new_tok.lang_token_to_id , A_ ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' __lowercase = """en""" __lowercase = """fr""" __lowercase = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=A_ , return_tensors="""pt""" ) __lowercase = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: __lowercase = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' __lowercase = """mr""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""mr""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) __lowercase = """zh""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""zh""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' __lowercase = """mr""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""mr""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) __lowercase = """zh""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""zh""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' __lowercase = self.tokenizer._build_translation_inputs("""A test""" , return_tensors="""pt""" , src_lang="""en""" , tgt_lang="""ar""" ) self.assertEqual( nested_simplify(A_ ) , { # en_XX, A, test, EOS """input_ids""": [[1_2_8_0_2_2, 5_8, 4_1_8_3, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 1_2_8_0_0_6, } , )
442
"""simple docstring""" from typing import List from .keymap import KEYMAP, get_character def lowerCAmelCase_ ( UpperCamelCase__ : str ): """simple docstring""" def decorator(UpperCamelCase__ : Tuple ): __lowercase = getattr(UpperCamelCase__ , """handle_key""" , [] ) handle += [key] setattr(UpperCamelCase__ , """handle_key""" , UpperCamelCase__ ) return func return decorator def lowerCAmelCase_ ( *UpperCamelCase__ : List[str] ): """simple docstring""" def decorator(UpperCamelCase__ : Tuple ): __lowercase = getattr(UpperCamelCase__ , """handle_key""" , [] ) handle += keys setattr(UpperCamelCase__ , """handle_key""" , UpperCamelCase__ ) return func return decorator class lowerCamelCase__ ( _a ): def __new__( cls : str , A_ : Optional[Any] , A_ : Union[str, Any] , A_ : int ): '''simple docstring''' __lowercase = super().__new__(cls , A_ , A_ , A_ ) if not hasattr(A_ , """key_handler""" ): setattr(A_ , """key_handler""" , {} ) setattr(A_ , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): __lowercase = getattr(A_ , """handle_key""" , [] ) for key in handled_keys: __lowercase = value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : Dict ): '''simple docstring''' __lowercase = get_character() if char != KEYMAP["undefined"]: __lowercase = ord(A_ ) __lowercase = cls.key_handler.get(A_ ) if handler: __lowercase = char return handler(cls ) else: return None def lowerCAmelCase_ ( cls : int ): """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
442
1
'''simple docstring''' import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) _a : Optional[Any] = logging.getLogger(__name__) _a : str = tf.data.AUTOTUNE def _lowerCAmelCase ( ) -> Tuple: __lowerCAmelCase = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=lowercase , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=lowercase , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=lowercase , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=lowercase , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=lowercase , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=lowercase , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=lowercase , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=lowercase , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=lowercase , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=lowercase , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=lowercase , default=1e-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=lowercase , default=1e-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=lowercase , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=lowercase , default=0.15 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=lowercase , required=lowercase , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=lowercase , help="""Model ID to upload to on the Hugging Face Hub.""" ) __lowerCAmelCase = parser.parse_args() return args def _lowerCAmelCase ( lowercase ) -> int: try: if args.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(lowercase ) tf.tpu.experimental.initialize_tpu_system(lowercase ) return tpu def _lowerCAmelCase ( lowercase ) -> List[str]: __lowerCAmelCase = 0 for file in file_list: __lowerCAmelCase = file.split("""/""" )[-1] __lowerCAmelCase = re.search(R"""-\d+-(\d+)\.tfrecord""" , lowercase ).group(1 ) __lowerCAmelCase = int(lowercase ) num_samples += sample_count return num_samples def _lowerCAmelCase ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase=None ) -> Any: __lowerCAmelCase = count_samples(lowercase ) __lowerCAmelCase = tf.data.Dataset.from_tensor_slices(lowercase ) if shuffle: __lowerCAmelCase = dataset.shuffle(len(lowercase ) ) __lowerCAmelCase = tf.data.TFRecordDataset(lowercase , num_parallel_reads=lowercase ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here __lowerCAmelCase = dataset.apply(tf.data.experimental.assert_cardinality(lowercase ) ) __lowerCAmelCase = dataset.map(lowercase , num_parallel_calls=lowercase ) if shuffle: assert shuffle_buffer_size is not None __lowerCAmelCase = dataset.shuffle(args.shuffle_buffer_size ) __lowerCAmelCase = dataset.batch(lowercase , drop_remainder=lowercase ) __lowerCAmelCase = dataset.map(lowercase , num_parallel_calls=lowercase ) __lowerCAmelCase = dataset.prefetch(lowercase ) return dataset def _lowerCAmelCase ( lowercase ) -> int: if not args.no_tpu: __lowerCAmelCase = initialize_tpu(lowercase ) __lowerCAmelCase = tf.distribute.TPUStrategy(lowercase ) else: __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) __lowerCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer ) __lowerCAmelCase = AutoConfig.from_pretrained(args.pretrained_model_config ) __lowerCAmelCase = tokenizer.vocab_size __lowerCAmelCase = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(f'No .tfrecord files found in {args.train_dataset}.' ) __lowerCAmelCase = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(f'No .tfrecord files found in {args.eval_dataset}.' ) __lowerCAmelCase = count_samples(lowercase ) __lowerCAmelCase = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) __lowerCAmelCase = steps_per_epoch * args.num_epochs with strategy.scope(): __lowerCAmelCase = TFAutoModelForMaskedLM.from_config(lowercase ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built __lowerCAmelCase , __lowerCAmelCase = create_optimizer( num_train_steps=lowercase , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=lowercase , metrics=["""accuracy"""] ) def decode_fn(lowercase ): __lowerCAmelCase = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(lowercase , lowercase ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. __lowerCAmelCase = DataCollatorForLanguageModeling( tokenizer=lowercase , mlm_probability=args.mlm_probability , mlm=lowercase , return_tensors="""tf""" ) def mask_with_collator(lowercase ): # TF really needs an isin() function __lowerCAmelCase = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) __lowerCAmelCase , __lowerCAmelCase = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(lowercase ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=lowercase , ) return batch __lowerCAmelCase = args.per_replica_batch_size * strategy.num_replicas_in_sync __lowerCAmelCase = prepare_dataset( lowercase , decode_fn=lowercase , mask_fn=lowercase , batch_size=lowercase , shuffle=lowercase , shuffle_buffer_size=args.shuffle_buffer_size , ) __lowerCAmelCase = prepare_dataset( lowercase , decode_fn=lowercase , mask_fn=lowercase , batch_size=lowercase , shuffle=lowercase , ) __lowerCAmelCase = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=lowercase ) ) model.fit( lowercase , validation_data=lowercase , epochs=args.num_epochs , callbacks=lowercase , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": _a : Any = parse_args() main(args)
689
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features _a : Optional[int] = logging.get_logger(__name__) _a : int = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) _a : str = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _UpperCAmelCase : a : str =field( default=lowerCAmelCase_ , metadata={"""help""": """Model type selected in the list: """ + """, """.join(lowerCAmelCase_ )} ) a : str =field( default=lowerCAmelCase_ , metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""} ) a : int =field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a : int =field( default=1_28 , metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""} , ) a : int =field( default=64 , metadata={ """help""": ( """The maximum number of tokens for the question. Questions longer than this will """ """be truncated to this length.""" ) } , ) a : int =field( default=30 , metadata={ """help""": ( """The maximum length of an answer that can be generated. This is needed because the start """ """and end predictions are not conditioned on one another.""" ) } , ) a : bool =field( default=lowerCAmelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) a : bool =field( default=lowerCAmelCase_ , metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""} ) a : float =field( default=0.0 , metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""} ) a : int =field( default=20 , metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""} ) a : int =field( default=0 , metadata={ """help""": ( """language id of input for language-specific xlm models (see""" """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)""" ) } , ) a : int =field(default=1 , metadata={"""help""": """multiple threads for converting example to features"""} ) class _UpperCAmelCase ( lowerCAmelCase_ ): a : Optional[Any] ="""train""" a : Optional[int] ="""dev""" class _UpperCAmelCase ( lowerCAmelCase_ ): a : SquadDataTrainingArguments a : List[SquadFeatures] a : Split a : bool def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = Split.train,__SCREAMING_SNAKE_CASE = False,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = "pt",): '''simple docstring''' __lowerCAmelCase = args __lowerCAmelCase = is_language_sensitive __lowerCAmelCase = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): try: __lowerCAmelCase = Split[mode] except KeyError: raise KeyError("""mode is not a valid split name""" ) __lowerCAmelCase = mode # Load data features from cache or dataset file __lowerCAmelCase = """v2""" if args.version_2_with_negative else """v1""" __lowerCAmelCase = os.path.join( cache_dir if cache_dir is not None else args.data_dir,f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}',) # 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(__SCREAMING_SNAKE_CASE ): if os.path.exists(__SCREAMING_SNAKE_CASE ) and not args.overwrite_cache: __lowerCAmelCase = time.time() __lowerCAmelCase = torch.load(__SCREAMING_SNAKE_CASE ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. __lowerCAmelCase = self.old_features["""features"""] __lowerCAmelCase = self.old_features.get("""dataset""",__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = self.old_features.get("""examples""",__SCREAMING_SNAKE_CASE ) logger.info( f'Loading features from cached file {cached_features_file} [took %.3f s]',time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in' """ future run""" ) else: if mode == Split.dev: __lowerCAmelCase = self.processor.get_dev_examples(args.data_dir ) else: __lowerCAmelCase = self.processor.get_train_examples(args.data_dir ) __lowerCAmelCase , __lowerCAmelCase = squad_convert_examples_to_features( examples=self.examples,tokenizer=__SCREAMING_SNAKE_CASE,max_seq_length=args.max_seq_length,doc_stride=args.doc_stride,max_query_length=args.max_query_length,is_training=mode == Split.train,threads=args.threads,return_dataset=__SCREAMING_SNAKE_CASE,) __lowerCAmelCase = time.time() torch.save( {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples},__SCREAMING_SNAKE_CASE,) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' ) def __len__( self ): '''simple docstring''' return len(self.features ) def __getitem__( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = self.features[i] __lowerCAmelCase = torch.tensor(feature.input_ids,dtype=torch.long ) __lowerCAmelCase = torch.tensor(feature.attention_mask,dtype=torch.long ) __lowerCAmelCase = torch.tensor(feature.token_type_ids,dtype=torch.long ) __lowerCAmelCase = torch.tensor(feature.cls_index,dtype=torch.long ) __lowerCAmelCase = torch.tensor(feature.p_mask,dtype=torch.float ) __lowerCAmelCase = torch.tensor(feature.is_impossible,dtype=torch.float ) __lowerCAmelCase = { """input_ids""": input_ids, """attention_mask""": attention_mask, """token_type_ids""": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask} ) if self.args.version_2_with_negative: inputs.update({"""is_impossible""": is_impossible} ) if self.is_language_sensitive: inputs.update({"""langs""": (torch.ones(input_ids.shape,dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: __lowerCAmelCase = torch.tensor(feature.start_position,dtype=torch.long ) __lowerCAmelCase = torch.tensor(feature.end_position,dtype=torch.long ) inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions} ) return inputs
689
1
'''simple docstring''' import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __UpperCamelCase ( lowercase__ , unittest.TestCase ): lowercase : Optional[int] = VideoToVideoSDPipeline lowercase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'} ) - {'image', 'width', 'height'} lowercase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'} ) - {'image'} lowercase : str = PipelineTesterMixin.required_optional_params - {'latents'} lowercase : Optional[int] = False # No `output_type`. lowercase : List[str] = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'return_dict', 'callback', 'callback_steps', ] ) def a__ ( self :Tuple ): torch.manual_seed(0 ) snake_case_ : Any = UNetaDConditionModel( block_out_channels=(3_2, 6_4, 6_4, 6_4) ,layers_per_block=2 ,sample_size=3_2 ,in_channels=4 ,out_channels=4 ,down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") ,up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") ,cross_attention_dim=3_2 ,attention_head_dim=4 ,) snake_case_ : List[Any] = DDIMScheduler( beta_start=0.0_00_85 ,beta_end=0.0_12 ,beta_schedule="""scaled_linear""" ,clip_sample=__a ,set_alpha_to_one=__a ,) torch.manual_seed(0 ) snake_case_ : List[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 ) snake_case_ : Tuple = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=3_2 ,intermediate_size=3_7 ,layer_norm_eps=1E-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,hidden_act="""gelu""" ,projection_dim=5_1_2 ,) snake_case_ : List[Any] = CLIPTextModel(__a ) snake_case_ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) snake_case_ : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def a__ ( self :List[Any] ,_UpperCamelCase :List[str] ,_UpperCamelCase :str=0 ): snake_case_ : Dict = floats_tensor((1, 3, 3, 3_2, 3_2) ,rng=random.Random(__a ) ).to(__a ) if str(__a ).startswith("""mps""" ): snake_case_ : int = torch.manual_seed(__a ) else: snake_case_ : Any = torch.Generator(device=__a ).manual_seed(__a ) snake_case_ : int = { """prompt""": """A painting of a squirrel eating a burger""", """video""": video, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def a__ ( self :str ): snake_case_ : Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator snake_case_ : Any = self.get_dummy_components() snake_case_ : List[str] = VideoToVideoSDPipeline(**__a ) snake_case_ : Union[str, Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) snake_case_ : Dict = self.get_dummy_inputs(__a ) snake_case_ : Optional[Any] = """np""" snake_case_ : List[str] = sd_pipe(**__a ).frames snake_case_ : int = frames[0][-3:, -3:, -1] assert frames[0].shape == (3_2, 3_2, 3) snake_case_ : Optional[Any] = np.array([1_0_6, 1_1_7, 1_1_3, 1_7_4, 1_3_7, 1_1_2, 1_4_8, 1_5_1, 1_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def a__ ( self :Union[str, Any] ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a ,expected_max_diff=5E-3 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def a__ ( self :List[str] ): pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def a__ ( self :Optional[int] ): pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def a__ ( self :Tuple ): pass def a__ ( self :Optional[Any] ): return super().test_progress_bar() @slow @skip_mps class __UpperCamelCase ( unittest.TestCase ): def a__ ( self :List[Any] ): snake_case_ : Union[str, Any] = VideoToVideoSDPipeline.from_pretrained("""cerspense/zeroscope_v2_XL""" ,torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames snake_case_ : str = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ : str = torch.randn((1, 1_0, 3, 1_0_2_4, 5_7_6) ,generator=__a ) snake_case_ : int = video.to("""cuda""" ) snake_case_ : List[Any] = """Spiderman is surfing""" snake_case_ : Union[str, Any] = pipe(__a ,video=__a ,generator=__a ,num_inference_steps=3 ,output_type="""pt""" ).frames snake_case_ : int = np.array([-1.0_45_89_84, -1.1_27_92_97, -0.9_66_30_86, -0.91_50_39_06, -0.75_09_76_56] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
712
'''simple docstring''' import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __A : List[Any] = logging.get_logger(__name__) def UpperCAmelCase ( lowerCamelCase_ :nn.ModuleList , lowerCamelCase_ :nn.ModuleList , lowerCamelCase_ :List[int] ): '''simple docstring''' snake_case_ : Optional[Any] = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(lowerCamelCase_ ) == len(lowerCamelCase_ ), F'''{len(lowerCamelCase_ )} != {len(lowerCamelCase_ )}''' dest_layers.load_state_dict(layers_to_copy.state_dict() ) __A : Optional[int] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __A : Dict = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def UpperCAmelCase ( lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :int ): '''simple docstring''' try: snake_case_ : int = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F'''no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first''' F''' {n_student}''' ) return list(range(lowerCamelCase_ ) ) def UpperCAmelCase ( lowerCamelCase_ :List[Any] , lowerCamelCase_ :List[Any] ): '''simple docstring''' if n_student > n_teacher: raise ValueError(F'''Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}''' ) elif n_teacher == n_student: return list(range(lowerCamelCase_ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def UpperCAmelCase ( lowerCamelCase_ :Union[str, PreTrainedModel] , lowerCamelCase_ :Union[str, Path] = "student" , lowerCamelCase_ :Union[int, None] = None , lowerCamelCase_ :Union[int, None] = None , lowerCamelCase_ :List[str]=False , lowerCamelCase_ :Optional[int]=None , lowerCamelCase_ :Optional[Any]=None , **lowerCamelCase_ :Dict , ): '''simple docstring''' snake_case_ : Optional[Any] = """encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.""" assert (e is not None) or (d is not None), _msg if isinstance(lowerCamelCase_ , lowerCamelCase_ ): AutoTokenizer.from_pretrained(lowerCamelCase_ ).save_pretrained(lowerCamelCase_ ) # purely for convenience snake_case_ : List[Any] = AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase_ ).eval() else: assert isinstance(lowerCamelCase_ , lowerCamelCase_ ), F'''teacher must be a model or string got type {type(lowerCamelCase_ )}''' snake_case_ : Any = teacher.config.to_diff_dict() try: snake_case_ , snake_case_ : List[str] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: snake_case_ : Dict = teacher_e if d is None: snake_case_ : List[Any] = teacher_d init_kwargs.update({"""encoder_layers""": e, """decoder_layers""": d} ) except AttributeError: # T5 if hasattr(teacher.config , """num_encoder_layers""" ): snake_case_ , snake_case_ : Tuple = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: snake_case_ , snake_case_ : Union[str, Any] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: snake_case_ : Optional[int] = teacher_e if d is None: snake_case_ : List[str] = teacher_d if hasattr(teacher.config , """num_encoder_layers""" ): init_kwargs.update({"""num_encoder_layers""": e, """num_decoder_layers""": d} ) else: init_kwargs.update({"""num_layers""": e, """num_decoder_layers""": d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(lowerCamelCase_ ) # Copy weights snake_case_ : List[Any] = teacher.config_class(**lowerCamelCase_ ) snake_case_ : Tuple = AutoModelForSeqaSeqLM.from_config(lowerCamelCase_ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. snake_case_ : Tuple = student.load_state_dict(teacher.state_dict() , strict=lowerCamelCase_ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save snake_case_ , snake_case_ : List[str] = list(range(lowerCamelCase_ ) ), list(range(lowerCamelCase_ ) ) logger.info( F'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to''' F''' {save_path}''' ) student.save_pretrained(lowerCamelCase_ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: snake_case_ : List[int] = pick_layers_to_copy(lowerCamelCase_ , lowerCamelCase_ ) if d_layers_to_copy is None: snake_case_ : List[int] = pick_layers_to_copy(lowerCamelCase_ , lowerCamelCase_ ) try: if hasattr( lowerCamelCase_ , """prophetnet""" ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , lowerCamelCase_ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , lowerCamelCase_ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , lowerCamelCase_ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , lowerCamelCase_ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , lowerCamelCase_ ) copy_layers(teacher.decoder.block , student.decoder.block , lowerCamelCase_ ) logger.info( F'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}''' ) snake_case_ : Any = { """teacher_type""": teacher.config.model_type, """copied_encoder_layers""": e_layers_to_copy, """copied_decoder_layers""": d_layers_to_copy, } student.save_pretrained(lowerCamelCase_ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
267
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __SCREAMING_SNAKE_CASE =False class UpperCamelCase ( unittest.TestCase ): pass @nightly @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' lowercase_ : str = VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion' ,torch_dtype=torch.floataa ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) lowercase_ : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) lowercase_ : int = torch.manual_seed(0 ) lowercase_ : Optional[int] = pipe.dual_guided( prompt='first prompt' ,image=__UpperCamelCase ,text_to_image_strength=0.75 ,generator=__UpperCamelCase ,guidance_scale=7.5 ,num_inference_steps=2 ,output_type='numpy' ,).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__UpperCamelCase ) lowercase_ : str = VersatileDiffusionPipeline.from_pretrained(__UpperCamelCase ,torch_dtype=torch.floataa ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) lowercase_ : List[Any] = generator.manual_seed(0 ) lowercase_ : Union[str, Any] = pipe.dual_guided( prompt='first prompt' ,image=__UpperCamelCase ,text_to_image_strength=0.75 ,generator=__UpperCamelCase ,guidance_scale=7.5 ,num_inference_steps=2 ,output_type='numpy' ,).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' lowercase_ : Any = VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion' ,torch_dtype=torch.floataa ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) lowercase_ : int = 'cyberpunk 2077' lowercase_ : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) lowercase_ : Optional[Any] = torch.manual_seed(0 ) lowercase_ : int = pipe.dual_guided( prompt=__UpperCamelCase ,image=__UpperCamelCase ,text_to_image_strength=0.75 ,generator=__UpperCamelCase ,guidance_scale=7.5 ,num_inference_steps=50 ,output_type='numpy' ,).images lowercase_ : int = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) lowercase_ : Union[str, Any] = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 lowercase_ : Optional[Any] = 'A painting of a squirrel eating a burger ' lowercase_ : Optional[Any] = torch.manual_seed(0 ) lowercase_ : Dict = pipe.text_to_image( prompt=__UpperCamelCase ,generator=__UpperCamelCase ,guidance_scale=7.5 ,num_inference_steps=50 ,output_type='numpy' ).images lowercase_ : Tuple = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) lowercase_ : Tuple = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 lowercase_ : Dict = pipe.image_variation(__UpperCamelCase ,generator=__UpperCamelCase ,output_type='numpy' ).images lowercase_ : Union[str, Any] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) lowercase_ : Union[str, Any] = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
425
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class UpperCamelCase ( lowercase_ , lowercase_ ): @register_to_config def __init__( self ,__UpperCamelCase = 768 ,) -> str: '''simple docstring''' super().__init__() lowercase_ : Union[str, Any] = nn.Parameter(torch.zeros(1 ,__UpperCamelCase ) ) lowercase_ : Optional[Any] = nn.Parameter(torch.ones(1 ,__UpperCamelCase ) ) def _UpperCAmelCase ( self ,__UpperCamelCase = None ,__UpperCamelCase = None ,) -> Tuple: '''simple docstring''' lowercase_ : Tuple = nn.Parameter(self.mean.to(__UpperCamelCase ).to(__UpperCamelCase ) ) lowercase_ : str = nn.Parameter(self.std.to(__UpperCamelCase ).to(__UpperCamelCase ) ) return self def _UpperCAmelCase ( self ,__UpperCamelCase ) -> str: '''simple docstring''' lowercase_ : Dict = (embeds - self.mean) * 1.0 / self.std return embeds def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Dict: '''simple docstring''' lowercase_ : Any = (embeds * self.std) + self.mean return embeds
425
1
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file _UpperCAmelCase : Union[str, Any] = "Run commands across TPU VMs for initial setup before running `accelerate launch`." def lowerCAmelCase_ (lowercase__ : Optional[int]=None ) -> List[str]: '''simple docstring''' if subparsers is not None: lowerCAmelCase__ = subparsers.add_parser('''tpu-config''' , description=_description ) else: lowerCAmelCase__ = argparse.ArgumentParser('''Accelerate tpu-config command''' , description=_description ) # Core arguments lowerCAmelCase__ = parser.add_argument_group( '''Config Arguments''' , '''Arguments that can be configured through `accelerate config`.''' ) config_args.add_argument( '''--config_file''' , type=lowercase__ , default=lowercase__ , help='''Path to the config file to use for accelerate.''' , ) config_args.add_argument( '''--tpu_name''' , default=lowercase__ , help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.''' , ) config_args.add_argument( '''--tpu_zone''' , default=lowercase__ , help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.''' , ) lowerCAmelCase__ = parser.add_argument_group('''TPU Arguments''' , '''Arguments for options ran inside the TPU.''' ) pod_args.add_argument( '''--use_alpha''' , action='''store_true''' , help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.''' , ) pod_args.add_argument( '''--command_file''' , default=lowercase__ , help='''The path to the file containing the commands to run on the pod on startup.''' , ) pod_args.add_argument( '''--command''' , action='''append''' , nargs='''+''' , help='''A command to run on the pod. Can be passed multiple times.''' , ) pod_args.add_argument( '''--install_accelerate''' , action='''store_true''' , help='''Whether to install accelerate on the pod. Defaults to False.''' , ) pod_args.add_argument( '''--accelerate_version''' , default='''latest''' , help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.''' , ) pod_args.add_argument( '''--debug''' , action='''store_true''' , help='''If set, will print the command that would be run instead of running it.''' ) if subparsers is not None: parser.set_defaults(func=lowercase__ ) return parser def lowerCAmelCase_ (lowercase__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowercase__ ): lowerCAmelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: lowerCAmelCase__ = defaults.command_file if not args.command and defaults.commands is not None: lowerCAmelCase__ = defaults.commands if not args.tpu_name: lowerCAmelCase__ = defaults.tpu_name if not args.tpu_zone: lowerCAmelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": lowerCAmelCase__ = '''git+https://github.com/huggingface/accelerate.git''' elif args.accelerate_version == "latest": lowerCAmelCase__ = '''accelerate -U''' elif isinstance(parse(args.accelerate_version ) , lowercase__ ): lowerCAmelCase__ = f'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('''You must specify either a command file or a command to run on the pod.''' ) if args.command_file: with open(args.command_file , '''r''' ) as f: lowerCAmelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowercase__ ): lowerCAmelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate lowerCAmelCase__ = ['''cd /usr/share'''] if args.install_accelerate: new_cmd += [f'pip install {args.accelerate_version}'] new_cmd += args.command lowerCAmelCase__ = '''; '''.join(lowercase__ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess lowerCAmelCase__ = ['''gcloud'''] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f'Running {" ".join(lowercase__ )}' ) return subprocess.run(lowercase__ ) print('''Successfully setup pod.''' ) def lowerCAmelCase_ () -> str: '''simple docstring''' lowerCAmelCase__ = tpu_command_parser() lowerCAmelCase__ = parser.parse_args() tpu_command_launcher(lowercase__ )
717
from __future__ import annotations def lowerCAmelCase_ (lowercase__ : list[int] ) -> bool: '''simple docstring''' return len(set(lowercase__ ) ) == len(lowercase__ ) if __name__ == "__main__": import doctest doctest.testmod()
288
0
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__=True, UpperCAmelCase__="pt" ) -> Optional[Any]: A_ = {"""add_prefix_space""": True} if isinstance(UpperCAmelCase__, UpperCAmelCase__ ) and not line.startswith(""" """ ) else {} A_ = padding_side return tokenizer( [line], max_length=UpperCAmelCase__, padding="""max_length""" if pad_to_max_length else None, truncation=UpperCAmelCase__, return_tensors=UpperCAmelCase__, add_special_tokens=UpperCAmelCase__, **UpperCAmelCase__, ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__=None, ) -> str: A_ = input_ids.ne(UpperCAmelCase__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class A__ ( _snake_case ): def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__="train" , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__="" , ) -> Union[str, Any]: '''simple docstring''' super().__init__() A_ = Path(UpperCamelCase__ ).joinpath(type_path + """.source""" ) A_ = Path(UpperCamelCase__ ).joinpath(type_path + """.target""" ) A_ = self.get_char_lens(self.src_file ) A_ = max_source_length A_ = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' A_ = tokenizer A_ = prefix if n_obs is not None: A_ = self.src_lens[:n_obs] A_ = src_lang A_ = tgt_lang def __len__( self ) -> List[Any]: '''simple docstring''' return len(self.src_lens ) def __getitem__( self , UpperCamelCase__ ) -> Dict[str, torch.Tensor]: '''simple docstring''' A_ = index + 1 # linecache starts at 1 A_ = self.prefix + linecache.getline(str(self.src_file ) , UpperCamelCase__ ).rstrip("""\n""" ) A_ = linecache.getline(str(self.tgt_file ) , UpperCamelCase__ ).rstrip("""\n""" ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , UpperCamelCase__ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right A_ = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , UpperCamelCase__ ) else self.tokenizer ) A_ = self.tokenizer.generator if isinstance(self.tokenizer , UpperCamelCase__ ) else self.tokenizer A_ = encode_line(UpperCamelCase__ , UpperCamelCase__ , self.max_source_length , """right""" ) A_ = encode_line(UpperCamelCase__ , UpperCamelCase__ , self.max_target_length , """right""" ) A_ = source_inputs["""input_ids"""].squeeze() A_ = target_inputs["""input_ids"""].squeeze() A_ = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def snake_case_ ( UpperCamelCase__ ) -> Optional[int]: '''simple docstring''' return [len(UpperCamelCase__ ) for x in Path(UpperCamelCase__ ).open().readlines()] def snake_case_ ( self , UpperCamelCase__ ) -> Dict[str, torch.Tensor]: '''simple docstring''' A_ = torch.stack([x["""input_ids"""] for x in batch] ) A_ = torch.stack([x["""attention_mask"""] for x in batch] ) A_ = torch.stack([x["""decoder_input_ids"""] for x in batch] ) A_ = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , UpperCamelCase__ ) else self.tokenizer.pad_token_id ) A_ = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , UpperCamelCase__ ) else self.tokenizer.pad_token_id ) A_ = trim_batch(UpperCamelCase__ , UpperCamelCase__ ) A_ , A_ = trim_batch(UpperCamelCase__ , UpperCamelCase__ , attention_mask=UpperCamelCase__ ) A_ = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch __lowerCamelCase = getLogger(__name__) def UpperCAmelCase__ ( UpperCAmelCase__ ) -> Optional[int]: return list(itertools.chain.from_iterable(UpperCAmelCase__ ) ) def UpperCAmelCase__ ( UpperCAmelCase__ ) -> None: A_ = get_git_info() save_json(UpperCAmelCase__, os.path.join(UpperCAmelCase__, """git_log.json""" ) ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__=4, **UpperCAmelCase__ ) -> Dict: with open(UpperCAmelCase__, """w""" ) as f: json.dump(UpperCAmelCase__, UpperCAmelCase__, indent=UpperCAmelCase__, **UpperCAmelCase__ ) def UpperCAmelCase__ ( UpperCAmelCase__ ) -> Tuple: with open(UpperCAmelCase__ ) as f: return json.load(UpperCAmelCase__ ) def UpperCAmelCase__ ( ) -> Tuple: A_ = git.Repo(search_parent_directories=UpperCAmelCase__ ) A_ = { """repo_id""": str(UpperCAmelCase__ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> List: return list(map(UpperCAmelCase__, UpperCAmelCase__ ) ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> Optional[Any]: with open(UpperCAmelCase__, """wb""" ) as f: return pickle.dump(UpperCAmelCase__, UpperCAmelCase__ ) def UpperCAmelCase__ ( UpperCAmelCase__ ) -> List[str]: def remove_articles(UpperCAmelCase__ ): return re.sub(r"""\b(a|an|the)\b""", """ """, UpperCAmelCase__ ) def white_space_fix(UpperCAmelCase__ ): return " ".join(text.split() ) def remove_punc(UpperCAmelCase__ ): A_ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCAmelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(UpperCAmelCase__ ) ) ) ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> Union[str, Any]: A_ = normalize_answer(UpperCAmelCase__ ).split() A_ = normalize_answer(UpperCAmelCase__ ).split() A_ = Counter(UpperCAmelCase__ ) & Counter(UpperCAmelCase__ ) A_ = sum(common.values() ) if num_same == 0: return 0 A_ = 1.0 * num_same / len(UpperCAmelCase__ ) A_ = 1.0 * num_same / len(UpperCAmelCase__ ) A_ = (2 * precision * recall) / (precision + recall) return fa def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> List[str]: return normalize_answer(UpperCAmelCase__ ) == normalize_answer(UpperCAmelCase__ ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> Dict: assert len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) A_ = 0 for hypo, pred in zip(UpperCAmelCase__, UpperCAmelCase__ ): em += exact_match_score(UpperCAmelCase__, UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 0: em /= len(UpperCAmelCase__ ) return {"em": em} def UpperCAmelCase__ ( UpperCAmelCase__ ) -> Any: return model_prefix.startswith("""rag""" ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) -> Optional[Any]: A_ = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead A_ = """dropout_rate""" for p in extra_params: if getattr(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ): if not hasattr(UpperCAmelCase__, UpperCAmelCase__ ) and not hasattr(UpperCAmelCase__, equivalent_param[p] ): logger.info("""config doesn't have a `{}` attribute""".format(UpperCAmelCase__ ) ) delattr(UpperCAmelCase__, UpperCAmelCase__ ) continue A_ = p if hasattr(UpperCAmelCase__, UpperCAmelCase__ ) else equivalent_param[p] setattr(UpperCAmelCase__, UpperCAmelCase__, getattr(UpperCAmelCase__, UpperCAmelCase__ ) ) delattr(UpperCAmelCase__, UpperCAmelCase__ ) return hparams, config
288
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : def __init__( self , UpperCamelCase__ , UpperCamelCase__=12 , UpperCamelCase__=7 , UpperCamelCase__=True , UpperCamelCase__=True , UpperCamelCase__=True , UpperCamelCase__=99 , UpperCamelCase__=32 , UpperCamelCase__=32 , UpperCamelCase__=2 , UpperCamelCase__=4 , UpperCamelCase__=37 , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=0.02 , UpperCamelCase__=0 , UpperCamelCase__=None , ) -> Union[str, Any]: '''simple docstring''' A_ = parent A_ = batch_size A_ = seq_length A_ = is_training A_ = use_input_mask A_ = use_labels A_ = vocab_size A_ = hidden_size A_ = projection_dim A_ = num_hidden_layers A_ = num_attention_heads A_ = intermediate_size A_ = dropout A_ = attention_dropout A_ = max_position_embeddings A_ = initializer_range A_ = scope A_ = bos_token_id def snake_case_ ( self ) -> Dict: '''simple docstring''' A_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A_ = None if self.use_input_mask: A_ = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: A_ = input_mask.numpy() A_ , A_ = input_mask.shape A_ = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCamelCase__ ): A_ = 1 A_ = 0 A_ = self.get_config() return config, input_ids, tf.convert_to_tensor(UpperCamelCase__ ) def snake_case_ ( self ) -> Optional[int]: '''simple docstring''' return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> int: '''simple docstring''' A_ = TFBlipTextModel(config=UpperCamelCase__ ) A_ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , training=UpperCamelCase__ ) A_ = model(UpperCamelCase__ , training=UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def snake_case_ ( self ) -> List[Any]: '''simple docstring''' A_ = self.prepare_config_and_inputs() A_ , A_ , A_ = config_and_inputs A_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class A__ ( _snake_case , unittest.TestCase ): lowercase = (TFBlipTextModel,) if is_tf_available() else () lowercase = False lowercase = False lowercase = False def snake_case_ ( self ) -> Optional[int]: '''simple docstring''' A_ = BlipTextModelTester(self ) A_ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def snake_case_ ( self ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def snake_case_ ( self ) -> str: '''simple docstring''' A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def snake_case_ ( self ) -> List[Any]: '''simple docstring''' pass def snake_case_ ( self ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason="""Blip does not use inputs_embeds""" ) def snake_case_ ( self ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def snake_case_ ( self ) -> List[Any]: '''simple docstring''' pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def snake_case_ ( self ) -> Any: '''simple docstring''' pass @slow def snake_case_ ( self ) -> List[Any]: '''simple docstring''' for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ = TFBlipTextModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__=True ) -> str: '''simple docstring''' super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase__ )
288
1
"""simple docstring""" from __future__ import annotations def _UpperCAmelCase ( lowerCamelCase__ ): """simple docstring""" lowerCAmelCase__ = str(lowerCamelCase__ ) return len(lowerCamelCase__ ) == 9 and set(lowerCamelCase__ ) == set("""123456789""" ) def _UpperCAmelCase ( ): """simple docstring""" for base_num in range(9999 , 4999 , -1 ): lowerCAmelCase__ = 10_0002 * base_num if is_9_pandigital(lowerCamelCase__ ): return candidate for base_num in range(333 , 99 , -1 ): lowerCAmelCase__ = 100_2003 * base_num if is_9_pandigital(lowerCamelCase__ ): return candidate return None if __name__ == "__main__": print(F"{solution() = }")
674
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a_ ( __UpperCamelCase , unittest.TestCase ): UpperCamelCase_ : str = LayoutLMTokenizer UpperCamelCase_ : List[Any] = LayoutLMTokenizerFast UpperCamelCase_ : Dict = True UpperCamelCase_ : Any = True def _SCREAMING_SNAKE_CASE ( self : Tuple ): super().setUp() lowerCAmelCase__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _SCREAMING_SNAKE_CASE ( self : int , **snake_case__ : Union[str, Any] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **snake_case__ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , snake_case__ : Tuple ): lowerCAmelCase__ = """UNwant\u00E9d,running""" lowerCAmelCase__ = """unwanted, running""" return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): lowerCAmelCase__ = self.tokenizer_class(self.vocab_file ) lowerCAmelCase__ = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(snake_case__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) , [7, 4, 5, 10, 8, 9] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): pass
674
1
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowercase__ ( __lowercase : str , __lowercase : Union[str, Any] , __lowercase : List[str] , __lowercase : str , ) -> list[float]: """simple docstring""" __UpperCamelCase = coefficient_matrix.shape __UpperCamelCase = constant_matrix.shape if rowsa != colsa: __UpperCamelCase = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(A__ ) if colsa != 1: __UpperCamelCase = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(A__ ) if rowsa != rowsa: __UpperCamelCase = ( 'Coefficient and constant matrices dimensions must be nxn and nx1 but ' F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(A__ ) if len(A__ ) != rowsa: __UpperCamelCase = ( 'Number of initial values must be equal to number of rows in coefficient ' F'''matrix but received {len(A__ )} and {rowsa}''' ) raise ValueError(A__ ) if iterations <= 0: raise ValueError('Iterations must be at least 1' ) __UpperCamelCase = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) __UpperCamelCase = table.shape strictly_diagonally_dominant(A__ ) # Iterates the whole matrix for given number of times for _ in range(A__ ): __UpperCamelCase = [] for row in range(A__ ): __UpperCamelCase = 0 for col in range(A__ ): if col == row: __UpperCamelCase = table[row][col] elif col == cols - 1: __UpperCamelCase = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] __UpperCamelCase = (temp + val) / denom new_val.append(A__ ) __UpperCamelCase = new_val return [float(A__ ) for i in new_val] def lowercase__ ( __lowercase : Optional[int] ) -> bool: """simple docstring""" __UpperCamelCase = table.shape __UpperCamelCase = True for i in range(0 , A__ ): __UpperCamelCase = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('Coefficient matrix is not strictly diagonally dominant' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
399
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / """utils""")) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 lowercase : int = get_tests_dir("""fixtures""") class A__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : List[str] = mock.Mock() a__ : Any = 500 a__ : List[Any] = {} a__ : List[str] = HTTPError a__ : Optional[Any] = {} # Download this model to make sure it's in the cache. a__ : Dict = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit') # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=lowercase) as mock_head: a__ : str = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit') # This check we did call the fake head request mock_head.assert_called() def __lowercase ( self) -> Dict: '''simple docstring''' a__ : Optional[Any] = ViTImageProcessor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json') def __lowercase ( self) -> int: '''simple docstring''' with self.assertRaises(lowercase): # config is in subfolder, the following should not work without specifying the subfolder a__ : Optional[int] = AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants') a__ : int = AutoImageProcessor.from_pretrained( 'hf-internal-testing/stable-diffusion-all-variants' , subfolder='feature_extractor') self.assertIsNotNone(lowercase) @is_staging_test class A__ ( unittest.TestCase ): """simple docstring""" @classmethod def __lowercase ( cls) -> Dict: '''simple docstring''' a__ : Union[str, Any] = TOKEN HfFolder.save_token(lowercase) @classmethod def __lowercase ( cls) -> Optional[Any]: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-image-processor') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-image-processor-org') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-image-processor') except HTTPError: pass def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : str = ViTImageProcessor.from_pretrained(lowercase) image_processor.push_to_hub('test-image-processor' , use_auth_token=self._token) a__ : Dict = ViTImageProcessor.from_pretrained(F'{USER}/test-image-processor') for k, v in image_processor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase)) # Reset repo delete_repo(token=self._token , repo_id='test-image-processor') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( lowercase , repo_id='test-image-processor' , push_to_hub=lowercase , use_auth_token=self._token) a__ : List[str] = ViTImageProcessor.from_pretrained(F'{USER}/test-image-processor') for k, v in image_processor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase)) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : int = ViTImageProcessor.from_pretrained(lowercase) image_processor.push_to_hub('valid_org/test-image-processor' , use_auth_token=self._token) a__ : Any = ViTImageProcessor.from_pretrained('valid_org/test-image-processor') for k, v in image_processor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase)) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-image-processor') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( lowercase , repo_id='valid_org/test-image-processor-org' , push_to_hub=lowercase , use_auth_token=self._token) a__ : int = ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org') for k, v in image_processor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase)) def __lowercase ( self) -> List[str]: '''simple docstring''' CustomImageProcessor.register_for_auto_class() a__ : List[Any] = CustomImageProcessor.from_pretrained(lowercase) image_processor.push_to_hub('test-dynamic-image-processor' , use_auth_token=self._token) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'} , ) a__ : str = AutoImageProcessor.from_pretrained( F'{USER}/test-dynamic-image-processor' , trust_remote_code=lowercase) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , 'CustomImageProcessor')
302
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCAmelCase__ : str = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : Optional[int] = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys lowerCAmelCase__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
703
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class _A ( UpperCamelCase ): '''simple docstring''' _lowercase = 42 _lowercase = 42 class _A ( nn.Module ): '''simple docstring''' _lowercase = 42 _lowercase = (16, 32, 96, 256) _lowercase = jnp.floataa def __lowerCAmelCase ( self : Tuple )-> Any: snake_case__ : Union[str, Any] = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) snake_case__ : List[str] = [] for i in range(len(self.block_out_channels ) - 1 ): snake_case__ : List[str] = self.block_out_channels[i] snake_case__ : Union[str, Any] = self.block_out_channels[i + 1] snake_case__ : Optional[int] = nn.Conv( lowerCamelCase , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(lowerCamelCase ) snake_case__ : int = nn.Conv( lowerCamelCase , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(lowerCamelCase ) snake_case__ : Any = blocks snake_case__ : Union[str, Any] = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Union[str, Any] , lowerCamelCase : Any )-> Tuple: snake_case__ : int = self.conv_in(lowerCamelCase ) snake_case__ : Dict = nn.silu(lowerCamelCase ) for block in self.blocks: snake_case__ : Dict = block(lowerCamelCase ) snake_case__ : str = nn.silu(lowerCamelCase ) snake_case__ : Union[str, Any] = self.conv_out(lowerCamelCase ) return embedding @flax_register_to_config class _A ( nn.Module , UpperCamelCase , UpperCamelCase ): '''simple docstring''' _lowercase = 32 _lowercase = 4 _lowercase = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _lowercase = False _lowercase = (320, 640, 1280, 1280) _lowercase = 2 _lowercase = 8 _lowercase = None _lowercase = 1280 _lowercase = 0.0 _lowercase = False _lowercase = jnp.floataa _lowercase = True _lowercase = 0 _lowercase = "rgb" _lowercase = (16, 32, 96, 256) def __lowerCAmelCase ( self : Optional[int] , lowerCamelCase : jax.random.KeyArray )-> FrozenDict: # init input tensors snake_case__ : Union[str, Any] = (1, self.in_channels, self.sample_size, self.sample_size) snake_case__ : Dict = jnp.zeros(lowerCamelCase , dtype=jnp.floataa ) snake_case__ : str = jnp.ones((1,) , dtype=jnp.intaa ) snake_case__ : str = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) snake_case__ : Dict = (1, 3, self.sample_size * 8, self.sample_size * 8) snake_case__ : Optional[Any] = jnp.zeros(lowerCamelCase , dtype=jnp.floataa ) snake_case__ , snake_case__ : List[Any] = jax.random.split(lowerCamelCase ) snake_case__ : Optional[Any] = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase )["params"] def __lowerCAmelCase ( self : int )-> int: snake_case__ : List[Any] = self.block_out_channels snake_case__ : Union[str, Any] = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. snake_case__ : Any = self.num_attention_heads or self.attention_head_dim # input snake_case__ : Any = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time snake_case__ : List[str] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) snake_case__ : Union[str, Any] = FlaxTimestepEmbedding(lowerCamelCase , dtype=self.dtype ) snake_case__ : Tuple = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) snake_case__ : Union[str, Any] = self.only_cross_attention if isinstance(lowerCamelCase , lowerCamelCase ): snake_case__ : Dict = (only_cross_attention,) * len(self.down_block_types ) if isinstance(lowerCamelCase , lowerCamelCase ): snake_case__ : Union[str, Any] = (num_attention_heads,) * len(self.down_block_types ) # down snake_case__ : Optional[Any] = [] snake_case__ : str = [] snake_case__ : Tuple = block_out_channels[0] snake_case__ : Tuple = nn.Conv( lowerCamelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(lowerCamelCase ) for i, down_block_type in enumerate(self.down_block_types ): snake_case__ : Optional[int] = output_channel snake_case__ : int = block_out_channels[i] snake_case__ : Union[str, Any] = i == len(lowerCamelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": snake_case__ : int = FlaxCrossAttnDownBlockaD( in_channels=lowerCamelCase , out_channels=lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: snake_case__ : Any = FlaxDownBlockaD( in_channels=lowerCamelCase , out_channels=lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(lowerCamelCase ) for _ in range(self.layers_per_block ): snake_case__ : str = nn.Conv( lowerCamelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(lowerCamelCase ) if not is_final_block: snake_case__ : Tuple = nn.Conv( lowerCamelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(lowerCamelCase ) snake_case__ : Optional[Any] = down_blocks snake_case__ : List[str] = controlnet_down_blocks # mid snake_case__ : Union[str, Any] = block_out_channels[-1] snake_case__ : Optional[int] = FlaxUNetMidBlockaDCrossAttn( in_channels=lowerCamelCase , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) snake_case__ : Tuple = nn.Conv( lowerCamelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Optional[int] , lowerCamelCase : int , lowerCamelCase : List[Any] , lowerCamelCase : Dict , lowerCamelCase : Optional[int] , lowerCamelCase : float = 1.0 , lowerCamelCase : bool = True , lowerCamelCase : bool = False , )-> Union[FlaxControlNetOutput, Tuple]: snake_case__ : int = self.controlnet_conditioning_channel_order if channel_order == "bgr": snake_case__ : Union[str, Any] = jnp.flip(lowerCamelCase , axis=1 ) # 1. time if not isinstance(lowerCamelCase , jnp.ndarray ): snake_case__ : List[Any] = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(lowerCamelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: snake_case__ : Optional[int] = timesteps.astype(dtype=jnp.floataa ) snake_case__ : Optional[int] = jnp.expand_dims(lowerCamelCase , 0 ) snake_case__ : Any = self.time_proj(lowerCamelCase ) snake_case__ : List[Any] = self.time_embedding(lowerCamelCase ) # 2. pre-process snake_case__ : Dict = jnp.transpose(lowerCamelCase , (0, 2, 3, 1) ) snake_case__ : Any = self.conv_in(lowerCamelCase ) snake_case__ : Dict = jnp.transpose(lowerCamelCase , (0, 2, 3, 1) ) snake_case__ : str = self.controlnet_cond_embedding(lowerCamelCase ) sample += controlnet_cond # 3. down snake_case__ : Any = (sample,) for down_block in self.down_blocks: if isinstance(lowerCamelCase , lowerCamelCase ): snake_case__ , snake_case__ : List[str] = down_block(lowerCamelCase , lowerCamelCase , lowerCamelCase , deterministic=not train ) else: snake_case__ , snake_case__ : List[str] = down_block(lowerCamelCase , lowerCamelCase , deterministic=not train ) down_block_res_samples += res_samples # 4. mid snake_case__ : Optional[Any] = self.mid_block(lowerCamelCase , lowerCamelCase , lowerCamelCase , deterministic=not train ) # 5. contronet blocks snake_case__ : List[str] = () for down_block_res_sample, controlnet_block in zip(lowerCamelCase , self.controlnet_down_blocks ): snake_case__ : List[str] = controlnet_block(lowerCamelCase ) controlnet_down_block_res_samples += (down_block_res_sample,) snake_case__ : Optional[Any] = controlnet_down_block_res_samples snake_case__ : Optional[int] = self.controlnet_mid_block(lowerCamelCase ) # 6. scaling snake_case__ : Optional[Any] = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=lowerCamelCase , mid_block_res_sample=lowerCamelCase )
172
0
import math def _a ( ) -> Tuple: """simple docstring""" lowerCamelCase__ : Dict = input('''Enter message: ''' ) lowerCamelCase__ : List[str] = int(input(f"Enter key [2-{len(A__ ) - 1}]: " ) ) lowerCamelCase__ : List[Any] = input('''Encryption/Decryption [e/d]: ''' ) if mode.lower().startswith('''e''' ): lowerCamelCase__ : List[Any] = encrypt_message(A__ , A__ ) elif mode.lower().startswith('''d''' ): lowerCamelCase__ : Tuple = decrypt_message(A__ , A__ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}" ) def _a ( UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: """simple docstring""" lowerCamelCase__ : int = [''''''] * key for col in range(A__ ): lowerCamelCase__ : Union[str, Any] = col while pointer < len(A__ ): cipher_text[col] += message[pointer] pointer += key return "".join(A__ ) def _a ( UpperCAmelCase , UpperCAmelCase ) -> Optional[int]: """simple docstring""" lowerCamelCase__ : int = math.ceil(len(A__ ) / key ) lowerCamelCase__ : Optional[int] = key lowerCamelCase__ : int = (num_cols * num_rows) - len(A__ ) lowerCamelCase__ : List[str] = [''''''] * num_cols lowerCamelCase__ : Tuple = 0 lowerCamelCase__ : int = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): lowerCamelCase__ : Any = 0 row += 1 return "".join(A__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
315
import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() a__ : List[str] = logging.get_logger("transformers.models.encodec") a__ : Optional[Any] = { "quantizer.vq.layers.*._codebook.inited": "quantizer.layers.*.codebook.inited", "quantizer.vq.layers.*._codebook.cluster_size": "quantizer.layers.*.codebook.cluster_size", "quantizer.vq.layers.*._codebook.embed": "quantizer.layers.*.codebook.embed", "quantizer.vq.layers.*._codebook.embed_avg": "quantizer.layers.*.codebook.embed_avg", } a__ : int = { "encoder.model.0.conv.conv": "encoder.layers.0.conv", "encoder.model.1.block.1.conv.conv": "encoder.layers.1.block.1.conv", "encoder.model.1.block.3.conv.conv": "encoder.layers.1.block.3.conv", "encoder.model.1.shortcut.conv.conv": "encoder.layers.1.shortcut.conv", "encoder.model.3.conv.conv": "encoder.layers.3.conv", "encoder.model.4.block.1.conv.conv": "encoder.layers.4.block.1.conv", "encoder.model.4.block.3.conv.conv": "encoder.layers.4.block.3.conv", "encoder.model.4.shortcut.conv.conv": "encoder.layers.4.shortcut.conv", "encoder.model.6.conv.conv": "encoder.layers.6.conv", "encoder.model.7.block.1.conv.conv": "encoder.layers.7.block.1.conv", "encoder.model.7.block.3.conv.conv": "encoder.layers.7.block.3.conv", "encoder.model.7.shortcut.conv.conv": "encoder.layers.7.shortcut.conv", "encoder.model.9.conv.conv": "encoder.layers.9.conv", "encoder.model.10.block.1.conv.conv": "encoder.layers.10.block.1.conv", "encoder.model.10.block.3.conv.conv": "encoder.layers.10.block.3.conv", "encoder.model.10.shortcut.conv.conv": "encoder.layers.10.shortcut.conv", "encoder.model.12.conv.conv": "encoder.layers.12.conv", "encoder.model.13.lstm": "encoder.layers.13.lstm", "encoder.model.15.conv.conv": "encoder.layers.15.conv", } a__ : int = { "encoder.model.0.conv.norm": "encoder.layers.0.norm", "encoder.model.1.block.1.conv.norm": "encoder.layers.1.block.1.norm", "encoder.model.1.block.3.conv.norm": "encoder.layers.1.block.3.norm", "encoder.model.1.shortcut.conv.norm": "encoder.layers.1.shortcut.norm", "encoder.model.3.conv.norm": "encoder.layers.3.norm", "encoder.model.4.block.1.conv.norm": "encoder.layers.4.block.1.norm", "encoder.model.4.block.3.conv.norm": "encoder.layers.4.block.3.norm", "encoder.model.4.shortcut.conv.norm": "encoder.layers.4.shortcut.norm", "encoder.model.6.conv.norm": "encoder.layers.6.norm", "encoder.model.7.block.1.conv.norm": "encoder.layers.7.block.1.norm", "encoder.model.7.block.3.conv.norm": "encoder.layers.7.block.3.norm", "encoder.model.7.shortcut.conv.norm": "encoder.layers.7.shortcut.norm", "encoder.model.9.conv.norm": "encoder.layers.9.norm", "encoder.model.10.block.1.conv.norm": "encoder.layers.10.block.1.norm", "encoder.model.10.block.3.conv.norm": "encoder.layers.10.block.3.norm", "encoder.model.10.shortcut.conv.norm": "encoder.layers.10.shortcut.norm", "encoder.model.12.conv.norm": "encoder.layers.12.norm", "encoder.model.15.conv.norm": "encoder.layers.15.norm", } a__ : Dict = { "decoder.model.0.conv.conv": "decoder.layers.0.conv", "decoder.model.1.lstm": "decoder.layers.1.lstm", "decoder.model.3.convtr.convtr": "decoder.layers.3.conv", "decoder.model.4.block.1.conv.conv": "decoder.layers.4.block.1.conv", "decoder.model.4.block.3.conv.conv": "decoder.layers.4.block.3.conv", "decoder.model.4.shortcut.conv.conv": "decoder.layers.4.shortcut.conv", "decoder.model.6.convtr.convtr": "decoder.layers.6.conv", "decoder.model.7.block.1.conv.conv": "decoder.layers.7.block.1.conv", "decoder.model.7.block.3.conv.conv": "decoder.layers.7.block.3.conv", "decoder.model.7.shortcut.conv.conv": "decoder.layers.7.shortcut.conv", "decoder.model.9.convtr.convtr": "decoder.layers.9.conv", "decoder.model.10.block.1.conv.conv": "decoder.layers.10.block.1.conv", "decoder.model.10.block.3.conv.conv": "decoder.layers.10.block.3.conv", "decoder.model.10.shortcut.conv.conv": "decoder.layers.10.shortcut.conv", "decoder.model.12.convtr.convtr": "decoder.layers.12.conv", "decoder.model.13.block.1.conv.conv": "decoder.layers.13.block.1.conv", "decoder.model.13.block.3.conv.conv": "decoder.layers.13.block.3.conv", "decoder.model.13.shortcut.conv.conv": "decoder.layers.13.shortcut.conv", "decoder.model.15.conv.conv": "decoder.layers.15.conv", } a__ : Any = { "decoder.model.0.conv.norm": "decoder.layers.0.norm", "decoder.model.3.convtr.norm": "decoder.layers.3.norm", "decoder.model.4.block.1.conv.norm": "decoder.layers.4.block.1.norm", "decoder.model.4.block.3.conv.norm": "decoder.layers.4.block.3.norm", "decoder.model.4.shortcut.conv.norm": "decoder.layers.4.shortcut.norm", "decoder.model.6.convtr.norm": "decoder.layers.6.norm", "decoder.model.7.block.1.conv.norm": "decoder.layers.7.block.1.norm", "decoder.model.7.block.3.conv.norm": "decoder.layers.7.block.3.norm", "decoder.model.7.shortcut.conv.norm": "decoder.layers.7.shortcut.norm", "decoder.model.9.convtr.norm": "decoder.layers.9.norm", "decoder.model.10.block.1.conv.norm": "decoder.layers.10.block.1.norm", "decoder.model.10.block.3.conv.norm": "decoder.layers.10.block.3.norm", "decoder.model.10.shortcut.conv.norm": "decoder.layers.10.shortcut.norm", "decoder.model.12.convtr.norm": "decoder.layers.12.norm", "decoder.model.13.block.1.conv.norm": "decoder.layers.13.block.1.norm", "decoder.model.13.block.3.conv.norm": "decoder.layers.13.block.3.norm", "decoder.model.13.shortcut.conv.norm": "decoder.layers.13.shortcut.norm", "decoder.model.15.conv.norm": "decoder.layers.15.norm", } a__ : Tuple = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } a__ : List[str] = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } a__ : str = [] a__ : str = [] def _lowerCAmelCase ( A__ , A__ , A__ , A__ , A__ ): for attribute in key.split('.' ): lowercase__ = getattr(A__ , A__ ) if weight_type is not None: lowercase__ = getattr(A__ , A__ ).shape else: lowercase__ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": lowercase__ = value elif weight_type == "weight_g": lowercase__ = value elif weight_type == "weight_v": lowercase__ = value elif weight_type == "bias": lowercase__ = value elif weight_type == "running_mean": lowercase__ = value elif weight_type == "running_var": lowercase__ = value elif weight_type == "num_batches_tracked": lowercase__ = value elif weight_type == "weight_ih_l0": lowercase__ = value elif weight_type == "weight_hh_l0": lowercase__ = value elif weight_type == "bias_ih_l0": lowercase__ = value elif weight_type == "bias_hh_l0": lowercase__ = value elif weight_type == "weight_ih_l1": lowercase__ = value elif weight_type == "weight_hh_l1": lowercase__ = value elif weight_type == "bias_ih_l1": lowercase__ = value elif weight_type == "bias_hh_l1": lowercase__ = value else: lowercase__ = value logger.info(F'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' ) def _lowerCAmelCase ( A__ , A__ ): for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: lowercase__, lowercase__ = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _lowerCAmelCase ( A__ , A__ , A__ ): lowercase__ = [] if model_name == "encodec_24khz" or "encodec_32khz": lowercase__ = MAPPING_24K elif model_name == "encodec_48khz": lowercase__ = MAPPING_48K else: raise ValueError(F'''Unsupported model: {model_name}''' ) for name, value in orig_dict.items(): if should_ignore(A__ , A__ ): logger.info(F'''{name} was ignored''' ) continue lowercase__ = False for key, mapped_key in MAPPING.items(): if "*" in key: lowercase__, lowercase__ = key.split('.*.' ) if prefix in name and suffix in name: lowercase__ = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue lowercase__ = True if "*" in mapped_key: lowercase__ = name.split(A__ )[0].split('.' )[-2] lowercase__ = mapped_key.replace('*' , A__ ) if "weight_g" in name: lowercase__ = 'weight_g' elif "weight_v" in name: lowercase__ = 'weight_v' elif "weight_ih_l0" in name: lowercase__ = 'weight_ih_l0' elif "weight_hh_l0" in name: lowercase__ = 'weight_hh_l0' elif "bias_ih_l0" in name: lowercase__ = 'bias_ih_l0' elif "bias_hh_l0" in name: lowercase__ = 'bias_hh_l0' elif "weight_ih_l1" in name: lowercase__ = 'weight_ih_l1' elif "weight_hh_l1" in name: lowercase__ = 'weight_hh_l1' elif "bias_ih_l1" in name: lowercase__ = 'bias_ih_l1' elif "bias_hh_l1" in name: lowercase__ = 'bias_hh_l1' elif "bias" in name: lowercase__ = 'bias' elif "weight" in name: lowercase__ = 'weight' elif "running_mean" in name: lowercase__ = 'running_mean' elif "running_var" in name: lowercase__ = 'running_var' elif "num_batches_tracked" in name: lowercase__ = 'num_batches_tracked' else: lowercase__ = None set_recursively(A__ , A__ , A__ , A__ , A__ ) continue if not is_used: unused_weights.append(A__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) @torch.no_grad() def _lowerCAmelCase ( A__ , A__ , A__ , A__=None , A__=None , ): if config_path is not None: lowercase__ = EncodecConfig.from_pretrained(A__ ) else: lowercase__ = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": lowercase__ = [8, 5, 4, 4] lowercase__ = [2.2] lowercase__ = 64 lowercase__ = 32_000 lowercase__ = 2_048 lowercase__ = False lowercase__ = False lowercase__ = False elif model_name == "encodec_48khz": lowercase__ = [8, 5, 4, 2] lowercase__ = [3.0, 6.0, 12.0, 24.0] lowercase__ = 48_000 lowercase__ = 2 lowercase__ = False lowercase__ = 'time_group_norm' lowercase__ = True lowercase__ = 1.0 lowercase__ = 0.01 else: raise ValueError(F'''Unknown model name: {model_name}''' ) lowercase__ = EncodecModel(A__ ) lowercase__ = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(A__ ) lowercase__ = torch.load(A__ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights lowercase__ = original_checkpoint['best_state'] recursively_load_weights(A__ , A__ , A__ ) model.save_pretrained(A__ ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(A__ ) model.push_to_hub(A__ ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument( "--model", default="encodec_24khz", type=str, help="The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.", ) parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) a__ : Optional[int] = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
622
0
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class a_ ( a__ ): """simple docstring""" @slow @require_torch def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : int = EncoderDecoderModel.from_encoder_decoder_pretrained('''prajjwal1/bert-tiny''' , '''prajjwal1/bert-tiny''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = BertTokenizer.from_pretrained('''bert-base-uncased''' ) SCREAMING_SNAKE_CASE : Optional[Any] = bertabert.config.encoder.vocab_size SCREAMING_SNAKE_CASE : Tuple = tokenizer.sep_token_id SCREAMING_SNAKE_CASE : List[str] = tokenizer.cls_token_id SCREAMING_SNAKE_CASE : int = 128 SCREAMING_SNAKE_CASE : List[Any] = datasets.load_dataset('''cnn_dailymail''' , '''3.0.0''' , split='''train[:1%]''' ) SCREAMING_SNAKE_CASE : Optional[Any] = datasets.load_dataset('''cnn_dailymail''' , '''3.0.0''' , split='''validation[:1%]''' ) SCREAMING_SNAKE_CASE : List[str] = train_dataset.select(range(32 ) ) SCREAMING_SNAKE_CASE : str = val_dataset.select(range(16 ) ) SCREAMING_SNAKE_CASE : Optional[int] = 4 def _map_to_encoder_decoder_inputs(_lowerCamelCase ): # Tokenizer will automatically set [BOS] <text> [EOS] SCREAMING_SNAKE_CASE : List[Any] = tokenizer(batch['''article'''] , padding='''max_length''' , truncation=_lowerCamelCase , max_length=512 ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(batch['''highlights'''] , padding='''max_length''' , truncation=_lowerCamelCase , max_length=128 ) SCREAMING_SNAKE_CASE : Dict = inputs.input_ids SCREAMING_SNAKE_CASE : Union[str, Any] = inputs.attention_mask SCREAMING_SNAKE_CASE : Tuple = outputs.input_ids SCREAMING_SNAKE_CASE : Any = outputs.input_ids.copy() SCREAMING_SNAKE_CASE : Tuple = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch['''labels'''] ] SCREAMING_SNAKE_CASE : int = outputs.attention_mask assert all(len(_lowerCamelCase ) == 512 for x in inputs.input_ids ) assert all(len(_lowerCamelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Optional[Any] = pred.label_ids SCREAMING_SNAKE_CASE : str = pred.predictions # all unnecessary tokens are removed SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.batch_decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = sum([int(pred_str[i] == label_str[i] ) for i in range(len(_lowerCamelCase ) )] ) / len(_lowerCamelCase ) return {"accuracy": accuracy} # map train dataset SCREAMING_SNAKE_CASE : List[Any] = train_dataset.map( _map_to_encoder_decoder_inputs , batched=_lowerCamelCase , batch_size=_lowerCamelCase , remove_columns=['''article''', '''highlights'''] , ) train_dataset.set_format( type='''torch''' , columns=['''input_ids''', '''attention_mask''', '''decoder_input_ids''', '''decoder_attention_mask''', '''labels'''] , ) # same for validation dataset SCREAMING_SNAKE_CASE : Any = val_dataset.map( _map_to_encoder_decoder_inputs , batched=_lowerCamelCase , batch_size=_lowerCamelCase , remove_columns=['''article''', '''highlights'''] , ) val_dataset.set_format( type='''torch''' , columns=['''input_ids''', '''attention_mask''', '''decoder_input_ids''', '''decoder_attention_mask''', '''labels'''] , ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : List[Any] = SeqaSeqTrainingArguments( output_dir=_lowerCamelCase , per_device_train_batch_size=_lowerCamelCase , per_device_eval_batch_size=_lowerCamelCase , predict_with_generate=_lowerCamelCase , evaluation_strategy='''steps''' , do_train=_lowerCamelCase , do_eval=_lowerCamelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer SCREAMING_SNAKE_CASE : int = SeqaSeqTrainer( model=_lowerCamelCase , args=_lowerCamelCase , compute_metrics=_compute_metrics , train_dataset=_lowerCamelCase , eval_dataset=_lowerCamelCase , tokenizer=_lowerCamelCase , ) # start training trainer.train()
333
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = torch.load(a__ , map_location='''cpu''' ) SCREAMING_SNAKE_CASE : List[str] = chkpt['''model'''] # We have the base model one level deeper than the original XLM repository SCREAMING_SNAKE_CASE : Optional[Any] = {} for k, v in state_dict.items(): if "pred_layer" in k: SCREAMING_SNAKE_CASE : str = v else: SCREAMING_SNAKE_CASE : Dict = v SCREAMING_SNAKE_CASE : int = chkpt['''params'''] SCREAMING_SNAKE_CASE : Tuple = {n: v for n, v in config.items() if not isinstance(a__ , (torch.FloatTensor, numpy.ndarray) )} SCREAMING_SNAKE_CASE : List[str] = chkpt['''dico_word2id'''] SCREAMING_SNAKE_CASE : Optional[Any] = {s + '''</w>''' if s.find('''@@''' ) == -1 and i > 13 else s.replace('''@@''' , '''''' ): i for s, i in vocab.items()} # Save pytorch-model SCREAMING_SNAKE_CASE : List[Any] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE : Optional[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME SCREAMING_SNAKE_CASE : List[Any] = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''vocab_file'''] print(F"""Save PyTorch model to {pytorch_weights_dump_path}""" ) torch.save(a__ , a__ ) print(F"""Save configuration file to {pytorch_config_dump_path}""" ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(a__ , indent=2 ) + '''\n''' ) print(F"""Save vocab file to {pytorch_config_dump_path}""" ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(a__ , indent=2 ) + '''\n''' ) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--xlm_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) a__ : int = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
333
1
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> Tuple: def count_of_possible_combinations(snake_case ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(SCREAMING_SNAKE_CASE__ ) def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> str: def count_of_possible_combinations_with_dp_array( snake_case , snake_case ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] _UpperCAmelCase = sum( count_of_possible_combinations_with_dp_array(target - item , SCREAMING_SNAKE_CASE__ ) for item in array ) _UpperCAmelCase = answer return answer _UpperCAmelCase = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> Dict: _UpperCAmelCase = [0] * (target + 1) _UpperCAmelCase = 1 for i in range(1 , target + 1 ): for j in range(SCREAMING_SNAKE_CASE__ ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() a = 3 a = 5 a = [1, 2, 5] print(combination_sum_iv(n, array, target))
518
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :list[list[int]] = [] UpperCamelCase :list[int] = [] UpperCamelCase :List[str] = 0 UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return result def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ): if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , ) __snake_case = [3, 34, 4, 12, 5, 2] __snake_case = 9 __snake_case = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
658
0
from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class __lowerCAmelCase : _UpperCamelCase : Tuple = BlenderbotConfig _UpperCamelCase : Optional[Any] = {} _UpperCamelCase : List[Any] = """gelu""" def __init__( self , snake_case , snake_case=13 , snake_case=7 , snake_case=True , snake_case=False , snake_case=99 , snake_case=32 , snake_case=2 , snake_case=4 , snake_case=37 , snake_case=0.1 , snake_case=0.1 , snake_case=20 , snake_case=2 , snake_case=1 , snake_case=0 , ) -> Optional[int]: """simple docstring""" a__ : Any = parent a__ : Optional[Any] = batch_size a__ : Tuple = seq_length a__ : Dict = is_training a__ : Union[str, Any] = use_labels a__ : int = vocab_size a__ : Any = hidden_size a__ : Any = num_hidden_layers a__ : List[Any] = num_attention_heads a__ : List[str] = intermediate_size a__ : Optional[int] = hidden_dropout_prob a__ : List[Any] = attention_probs_dropout_prob a__ : Tuple = max_position_embeddings a__ : List[Any] = eos_token_id a__ : List[str] = pad_token_id a__ : List[Any] = bos_token_id def _snake_case ( self ) -> str: """simple docstring""" a__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) a__ : List[str] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) a__ : str = tf.concat([input_ids, eos_tensor] , axis=1 ) a__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Dict = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) a__ : Union[str, Any] = prepare_blenderbot_inputs_dict(snake_case , snake_case , snake_case ) return config, inputs_dict def _snake_case ( self , snake_case , snake_case ) -> Dict: """simple docstring""" a__ : Optional[int] = TFBlenderbotModel(config=snake_case ).get_decoder() a__ : Optional[int] = inputs_dict["input_ids"] a__ : Tuple = input_ids[:1, :] a__ : str = inputs_dict["attention_mask"][:1, :] a__ : Optional[int] = inputs_dict["head_mask"] a__ : Any = 1 # first forward pass a__ : str = model(snake_case , attention_mask=snake_case , head_mask=snake_case , use_cache=snake_case ) a__ , a__ : Any = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids a__ : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) a__ : Dict = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and a__ : Optional[int] = tf.concat([input_ids, next_tokens] , axis=-1 ) a__ : str = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) a__ : int = model(snake_case , attention_mask=snake_case )[0] a__ : Tuple = model(snake_case , attention_mask=snake_case , past_key_values=snake_case )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice a__ : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) a__ : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] a__ : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(snake_case , snake_case , rtol=1E-3 ) def _A ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if attention_mask is None: a__ : List[Any] = tf.cast(tf.math.not_equal(lowerCamelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: a__ : Union[str, Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: a__ : Union[str, Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: a__ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: a__ : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __lowerCAmelCase ( _UpperCamelCase ,_UpperCamelCase ,unittest.TestCase ): _UpperCamelCase : str = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () _UpperCamelCase : str = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () _UpperCamelCase : Dict = ( { """conversational""": TFBlenderbotForConditionalGeneration, """feature-extraction""": TFBlenderbotModel, """summarization""": TFBlenderbotForConditionalGeneration, """text2text-generation""": TFBlenderbotForConditionalGeneration, """translation""": TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) _UpperCamelCase : Any = True _UpperCamelCase : Union[str, Any] = False _UpperCamelCase : Dict = False def _snake_case ( self ) -> Dict: """simple docstring""" a__ : str = TFBlenderbotModelTester(self ) a__ : Optional[int] = ConfigTester(self , config_class=snake_case ) def _snake_case ( self ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self ) -> int: """simple docstring""" a__ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*snake_case ) @require_tokenizers @require_tf class __lowerCAmelCase ( unittest.TestCase ): _UpperCamelCase : Dict = ["""My friends are cool but they eat too many carbs."""] _UpperCamelCase : List[Any] = """facebook/blenderbot-400M-distill""" @cached_property def _snake_case ( self ) -> List[Any]: """simple docstring""" return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def _snake_case ( self ) -> Tuple: """simple docstring""" a__ : int = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def _snake_case ( self ) -> Optional[Any]: """simple docstring""" a__ : Optional[Any] = self.tokenizer(self.src_text , return_tensors="tf" ) a__ : Optional[Any] = self.model.generate( model_inputs.input_ids , ) a__ : Union[str, Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=snake_case )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
629
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : str = { """configuration_distilbert""": [ """DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DistilBertConfig""", """DistilBertOnnxConfig""", ], """tokenization_distilbert""": ["""DistilBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = ["""DistilBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ """DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DistilBertForMaskedLM""", """DistilBertForMultipleChoice""", """DistilBertForQuestionAnswering""", """DistilBertForSequenceClassification""", """DistilBertForTokenClassification""", """DistilBertModel""", """DistilBertPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ """TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFDistilBertForMaskedLM""", """TFDistilBertForMultipleChoice""", """TFDistilBertForQuestionAnswering""", """TFDistilBertForSequenceClassification""", """TFDistilBertForTokenClassification""", """TFDistilBertMainLayer""", """TFDistilBertModel""", """TFDistilBertPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ """FlaxDistilBertForMaskedLM""", """FlaxDistilBertForMultipleChoice""", """FlaxDistilBertForQuestionAnswering""", """FlaxDistilBertForSequenceClassification""", """FlaxDistilBertForTokenClassification""", """FlaxDistilBertModel""", """FlaxDistilBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
629
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( ) -> int: _UpperCAmelCase = 1_0 _UpperCAmelCase = datasets.Features( { """tokens""": datasets.Sequence(datasets.Value("""string""" ) ), """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""] ) ), """answers""": datasets.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), """id""": datasets.Value("""int64""" ), } ) _UpperCAmelCase = datasets.Dataset.from_dict( { """tokens""": [["""foo"""] * 5] * n, """labels""": [[1] * 5] * n, """answers""": [{"""answer_start""": [9_7], """text""": ["""1976"""]}] * 1_0, """id""": list(range(__snake_case ) ), } , features=__snake_case , ) return dataset @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> int: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """file.arrow""" ) dataset.map(cache_file_name=__snake_case ) return filename # FILE_CONTENT + files __a: int = '''\ Text data. Second line of data.''' @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Dict: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt""" _UpperCAmelCase = FILE_CONTENT with open(__snake_case , """w""" ) as f: f.write(__snake_case ) return filename @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Optional[int]: import bza _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.bz2""" _UpperCAmelCase = bytes(__snake_case , """utf-8""" ) with bza.open(__snake_case , """wb""" ) as f: f.write(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> int: import gzip _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """file.txt.gz""" ) _UpperCAmelCase = bytes(__snake_case , """utf-8""" ) with gzip.open(__snake_case , """wb""" ) as f: f.write(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Optional[int]: if datasets.config.LZ4_AVAILABLE: import lza.frame _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.lz4""" _UpperCAmelCase = bytes(__snake_case , """utf-8""" ) with lza.frame.open(__snake_case , """wb""" ) as f: f.write(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> List[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.7z""" with pyazr.SevenZipFile(__snake_case , """w""" ) as archive: archive.write(__snake_case , arcname=os.path.basename(__snake_case ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> Tuple: import tarfile _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.tar""" with tarfile.TarFile(__snake_case , """w""" ) as f: f.add(__snake_case , arcname=os.path.basename(__snake_case ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Union[str, Any]: import lzma _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.xz""" _UpperCAmelCase = bytes(__snake_case , """utf-8""" ) with lzma.open(__snake_case , """wb""" ) as f: f.write(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> Dict: import zipfile _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Tuple: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.zst""" _UpperCAmelCase = bytes(__snake_case , """utf-8""" ) with zstd.open(__snake_case , """wb""" ) as f: f.write(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> str: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.xml""" _UpperCAmelCase = textwrap.dedent( """\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <tmx version=\"1.4\"> <header segtype=\"sentence\" srclang=\"ca\" /> <body> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv> </tu> </body> </tmx>""" ) with open(__snake_case , """w""" ) as f: f.write(__snake_case ) return filename __a: Dict = [ {'''col_1''': '''0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''3''', '''col_2''': 3, '''col_3''': 3.0}, ] __a: Tuple = [ {'''col_1''': '''4''', '''col_2''': 4, '''col_3''': 4.0}, {'''col_1''': '''5''', '''col_2''': 5, '''col_3''': 5.0}, ] __a: List[str] = { '''col_1''': ['''0''', '''1''', '''2''', '''3'''], '''col_2''': [0, 1, 2, 3], '''col_3''': [0.0, 1.0, 2.0, 3.0], } __a: int = [ {'''col_3''': 0.0, '''col_1''': '''0''', '''col_2''': 0}, {'''col_3''': 1.0, '''col_1''': '''1''', '''col_2''': 1}, ] __a: Tuple = [ {'''col_1''': '''s0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''s1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''s2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''s3''', '''col_2''': 3, '''col_3''': 3.0}, ] @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: return DATA_DICT_OF_LISTS @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> str: _UpperCAmelCase = datasets.Dataset.from_dict(__snake_case ) _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.arrow""" ) dataset.map(cache_file_name=__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Optional[int]: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.sqlite""" ) with contextlib.closing(sqlitea.connect(__snake_case ) ) as con: _UpperCAmelCase = con.cursor() cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)""" ) for item in DATA: cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)""" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> str: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.csv""" ) with open(__snake_case , """w""" , newline="""""" ) as f: _UpperCAmelCase = csv.DictWriter(__snake_case , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Tuple: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.csv""" ) with open(__snake_case , """w""" , newline="""""" ) as f: _UpperCAmelCase = csv.DictWriter(__snake_case , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> Tuple: import bza _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.bz2""" with open(__snake_case , """rb""" ) as f: _UpperCAmelCase = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(__snake_case , """wb""" ) as f: f.write(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> List[Any]: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Optional[Any]: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.basename(csv_path.replace(""".csv""" , """.CSV""" ) ) ) f.write(__snake_case , arcname=os.path.basename(csva_path.replace(""".csv""" , """.CSV""" ) ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> int: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.csv.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.join("""main_dir""" , os.path.basename(__snake_case ) ) ) f.write(__snake_case , arcname=os.path.join("""main_dir""" , os.path.basename(__snake_case ) ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Union[str, Any]: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.parquet""" ) _UpperCAmelCase = pa.schema( { """col_1""": pa.string(), """col_2""": pa.intaa(), """col_3""": pa.floataa(), } ) with open(__snake_case , """wb""" ) as f: _UpperCAmelCase = pq.ParquetWriter(__snake_case , schema=__snake_case ) _UpperCAmelCase = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(__snake_case ) )] for k in DATA[0]} , schema=__snake_case ) writer.write_table(__snake_case ) writer.close() return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Dict: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) _UpperCAmelCase = {"""data""": DATA} with open(__snake_case , """w""" ) as f: json.dump(__snake_case , __snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Dict: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) _UpperCAmelCase = {"""data""": DATA_DICT_OF_LISTS} with open(__snake_case , """w""" ) as f: json.dump(__snake_case , __snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Tuple: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl""" ) with open(__snake_case , """w""" ) as f: for item in DATA: f.write(json.dumps(__snake_case ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Any: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.jsonl""" ) with open(__snake_case , """w""" ) as f: for item in DATA: f.write(json.dumps(__snake_case ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Union[str, Any]: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset_312.jsonl""" ) with open(__snake_case , """w""" ) as f: for item in DATA_312: f.write(json.dumps(__snake_case ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Dict: _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset-str.jsonl""" ) with open(__snake_case , """w""" ) as f: for item in DATA_STR: f.write(json.dumps(__snake_case ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> str: import gzip _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt.gz""" ) with open(__snake_case , """rb""" ) as orig_file: with gzip.open(__snake_case , """wb""" ) as zipped_file: zipped_file.writelines(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> str: import gzip _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.gz""" ) with open(__snake_case , """rb""" ) as orig_file: with gzip.open(__snake_case , """wb""" ) as zipped_file: zipped_file.writelines(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Dict: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case , __snake_case ) -> Tuple: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.join("""nested""" , os.path.basename(__snake_case ) ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Union[str, Any]: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.jsonl.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.join("""main_dir""" , os.path.basename(__snake_case ) ) ) f.write(__snake_case , arcname=os.path.join("""main_dir""" , os.path.basename(__snake_case ) ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> int: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.tar""" with tarfile.TarFile(__snake_case , """w""" ) as f: f.add(__snake_case , arcname=os.path.basename(__snake_case ) ) f.add(__snake_case , arcname=os.path.basename(__snake_case ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case , __snake_case ) -> int: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.tar""" with tarfile.TarFile(__snake_case , """w""" ) as f: f.add(__snake_case , arcname=os.path.join("""nested""" , os.path.basename(__snake_case ) ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Union[str, Any]: _UpperCAmelCase = ["""0""", """1""", """2""", """3"""] _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt""" ) with open(__snake_case , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> Union[str, Any]: _UpperCAmelCase = ["""0""", """1""", """2""", """3"""] _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.txt""" ) with open(__snake_case , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> str: _UpperCAmelCase = ["""0""", """1""", """2""", """3"""] _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.abc""" with open(__snake_case , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Optional[Any]: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.text.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Any: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.text.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.join("""main_dir""" , os.path.basename(__snake_case ) ) ) f.write(__snake_case , arcname=os.path.join("""main_dir""" , os.path.basename(__snake_case ) ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> str: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.ext.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.basename("""unsupported.ext""" ) ) f.write(__snake_case , arcname=os.path.basename("""unsupported_2.ext""" ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> str: _UpperCAmelCase = """\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""] ) _UpperCAmelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset_with_unicode_new_lines.txt""" ) with open(__snake_case , """w""" , encoding="""utf-8""" ) as f: f.write(__snake_case ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: return os.path.join("""tests""" , """features""" , """data""" , """test_image_rgb.jpg""" ) @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]: return os.path.join("""tests""" , """features""" , """data""" , """test_audio_44100.wav""" ) @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> Optional[Any]: _UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.img.zip""" with zipfile.ZipFile(__snake_case , """w""" ) as f: f.write(__snake_case , arcname=os.path.basename(__snake_case ) ) f.write(__snake_case , arcname=os.path.basename(__snake_case ).replace(""".jpg""" , """2.jpg""" ) ) return path @pytest.fixture(scope="""session""" ) def _SCREAMING_SNAKE_CASE ( __snake_case ) -> str: _UpperCAmelCase = tmp_path_factory.mktemp("""data_dir""" ) (data_dir / "subdir").mkdir() with open(data_dir / """subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 1_0 ) with open(data_dir / """subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 1_0 ) # hidden file with open(data_dir / """subdir""" / """.test.txt""" , """w""" ) as f: f.write("""bar\n""" * 1_0 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / """.subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 1_0 ) with open(data_dir / """.subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 1_0 ) return data_dir
108
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Optional[int] ): """simple docstring""" snake_case_ : List[Any] = args.pruning_method snake_case_ : Any = args.threshold snake_case_ : Optional[Any] = args.model_name_or_path.rstrip("""/""" ) snake_case_ : Optional[Any] = args.target_model_path print(f'Load fine-pruned model from {model_name_or_path}' ) snake_case_ : str = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , """pytorch_model.bin""" ) ) snake_case_ : Optional[int] = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: snake_case_ : Dict = tensor print(f'Copied layer {name}' ) elif "classifier" in name or "qa_output" in name: snake_case_ : List[Any] = tensor print(f'Copied layer {name}' ) elif "bias" in name: snake_case_ : Tuple = tensor print(f'Copied layer {name}' ) else: if pruning_method == "magnitude": snake_case_ : List[Any] = MagnitudeBinarizer.apply(inputs=SCREAMING_SNAKE_CASE__ , threshold=SCREAMING_SNAKE_CASE__ ) snake_case_ : int = tensor * mask print(f'Pruned layer {name}' ) elif pruning_method == "topK": if "mask_scores" in name: continue snake_case_ : List[str] = name[:-6] snake_case_ : int = model[f'{prefix_}mask_scores'] snake_case_ : Optional[Any] = TopKBinarizer.apply(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case_ : Optional[int] = tensor * mask print(f'Pruned layer {name}' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue snake_case_ : str = name[:-6] snake_case_ : str = model[f'{prefix_}mask_scores'] snake_case_ : List[str] = ThresholdBinarizer.apply(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case_ : Dict = tensor * mask print(f'Pruned layer {name}' ) elif pruning_method == "l0": if "mask_scores" in name: continue snake_case_ : List[Any] = name[:-6] snake_case_ : Optional[int] = model[f'{prefix_}mask_scores'] snake_case_ , snake_case_ : List[str] = -0.1, 1.1 snake_case_ : Optional[int] = torch.sigmoid(SCREAMING_SNAKE_CASE__ ) snake_case_ : Optional[int] = s * (r - l) + l snake_case_ : Tuple = s_bar.clamp(min=0.0 , max=1.0 ) snake_case_ : List[str] = tensor * mask print(f'Pruned layer {name}' ) else: raise ValueError("""Unknown pruning method""" ) if target_model_path is None: snake_case_ : int = os.path.join( os.path.dirname(SCREAMING_SNAKE_CASE__ ) , f'bertarized_{os.path.basename(SCREAMING_SNAKE_CASE__ )}' ) if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): shutil.copytree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'\nCreated folder {target_model_path}' ) torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , """pytorch_model.bin""" ) ) print("""\nPruned model saved! See you later!""" ) if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '''--pruning_method''', choices=['''l0''', '''magnitude''', '''topK''', '''sigmoied_threshold'''], type=str, required=True, help=( '''Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,''' ''' sigmoied_threshold = Soft movement pruning)''' ), ) parser.add_argument( '''--threshold''', type=float, required=False, help=( '''For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.''' '''For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.''' '''Not needed for `l0`''' ), ) parser.add_argument( '''--model_name_or_path''', type=str, required=True, help='''Folder containing the model that was previously fine-pruned''', ) parser.add_argument( '''--target_model_path''', default=None, type=str, required=False, help='''Folder containing the model that was previously fine-pruned''', ) a_ = parser.parse_args() main(args)
480
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def __lowerCamelCase ( __snake_case : str, __snake_case : Optional[int]=False ) -> Tuple: """simple docstring""" A__ : Optional[Any] =[] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"module.blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"module.blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (f"module.blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"module.blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"module.blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"module.blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"module.blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"module.blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"module.blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"module.blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" A__ : Dict =[(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def __lowerCamelCase ( __snake_case : Dict, __snake_case : Optional[Any], __snake_case : Any=False ) -> int: """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: A__ : Optional[int] ="""""" else: A__ : int ="""vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : List[Any] =state_dict.pop(f"module.blocks.{i}.attn.qkv.weight" ) A__ : Dict =state_dict.pop(f"module.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict A__ : List[Any] =in_proj_weight[ : config.hidden_size, : ] A__ : Any =in_proj_bias[: config.hidden_size] A__ : int =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Dict =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : Tuple =in_proj_weight[ -config.hidden_size :, : ] A__ : Any =in_proj_bias[-config.hidden_size :] def __lowerCamelCase ( __snake_case : Tuple ) -> List[str]: """simple docstring""" A__ : List[Any] =["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( __snake_case : Union[str, Any] ) -> List[Any]: """simple docstring""" A__ : int =[ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( __snake_case : int, __snake_case : int, __snake_case : Dict ) -> Optional[int]: """simple docstring""" A__ : Any =dct.pop(_SCREAMING_SNAKE_CASE ) A__ : Optional[int] =val def __lowerCamelCase ( __snake_case : str, __snake_case : Any ) -> List[str]: """simple docstring""" A__ : int =ViTMSNConfig() A__ : Optional[int] =1_000 A__ : str ="""datasets/huggingface/label-files""" A__ : Optional[int] ="""imagenet-1k-id2label.json""" A__ : List[Any] =json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ), """r""" ) ) A__ : Dict ={int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} A__ : Optional[Any] =idalabel A__ : Dict ={v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: A__ : str =384 A__ : str =1_536 A__ : List[str] =6 elif "l16" in checkpoint_url: A__ : int =1_024 A__ : Tuple =4_096 A__ : Tuple =24 A__ : Optional[int] =16 A__ : List[Any] =0.1 elif "b4" in checkpoint_url: A__ : List[str] =4 elif "l7" in checkpoint_url: A__ : Tuple =7 A__ : str =1_024 A__ : int =4_096 A__ : int =24 A__ : int =16 A__ : List[str] =0.1 A__ : Optional[Any] =ViTMSNModel(_SCREAMING_SNAKE_CASE ) A__ : Any =torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE, map_location="""cpu""" )["""target_encoder"""] A__ : Tuple =ViTImageProcessor(size=config.image_size ) remove_projection_head(_SCREAMING_SNAKE_CASE ) A__ : Union[str, Any] =create_rename_keys(_SCREAMING_SNAKE_CASE, base_model=_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, base_model=_SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) model.eval() A__ : int ="""http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : Tuple =Image.open(requests.get(_SCREAMING_SNAKE_CASE, stream=_SCREAMING_SNAKE_CASE ).raw ) A__ : Dict =ViTImageProcessor( size=config.image_size, image_mean=_SCREAMING_SNAKE_CASE, image_std=_SCREAMING_SNAKE_CASE ) A__ : int =image_processor(images=_SCREAMING_SNAKE_CASE, return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) A__ : int =model(**_SCREAMING_SNAKE_CASE ) A__ : str =outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: A__ : List[str] =torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] ) elif "b16" in checkpoint_url: A__ : Optional[Any] =torch.tensor([[14.28_89, -18.90_45, 11.72_81]] ) elif "l16" in checkpoint_url: A__ : List[str] =torch.tensor([[41.50_28, -22.86_81, 45.64_75]] ) elif "b4" in checkpoint_url: A__ : List[Any] =torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] ) else: A__ : Union[str, Any] =torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3], _SCREAMING_SNAKE_CASE, atol=1E-4 ) print(f"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __snake_case : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __snake_case : Any = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
702
'''simple docstring''' import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def lowercase__ ( self : Optional[Any] ) -> int: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() def lowercase__ ( self : Union[str, Any] ) -> str: '''simple docstring''' A__ : Any =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) A__ : Optional[Any] =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) A__ : Optional[int] ="""xvjiarui/stable-diffusion-2-inpainting""" A__ , A__ : List[str] =FlaxStableDiffusionInpaintPipeline.from_pretrained(lowerCAmelCase_ , safety_checker=lowerCAmelCase_ ) A__ : List[str] ="""Face of a yellow cat, high resolution, sitting on a park bench""" A__ : Optional[Any] =jax.random.PRNGKey(0 ) A__ : List[str] =50 A__ : List[str] =jax.device_count() A__ : List[str] =num_samples * [prompt] A__ : List[str] =num_samples * [init_image] A__ : Tuple =num_samples * [mask_image] A__ , A__ , A__ : List[Any] =pipeline.prepare_inputs(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # shard inputs and rng A__ : Dict =replicate(lowerCAmelCase_ ) A__ : Union[str, Any] =jax.random.split(lowerCAmelCase_ , jax.device_count() ) A__ : List[Any] =shard(lowerCAmelCase_ ) A__ : Union[str, Any] =shard(lowerCAmelCase_ ) A__ : str =shard(lowerCAmelCase_ ) A__ : List[str] =pipeline( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , jit=lowerCAmelCase_ ) A__ : List[Any] =output.images.reshape(lowerCAmelCase_ , 5_12 , 5_12 , 3 ) A__ : str =images[0, 2_53:2_56, 2_53:2_56, -1] A__ : Tuple =jnp.asarray(jax.device_get(image_slice.flatten() ) ) A__ : Optional[int] =jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
687
0
'''simple docstring''' import unittest import numpy as np def __a ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray | None = None , ): a__ : Union[str, Any] = np.shape(lowerCAmelCase__ ) a__ : Tuple = np.shape(lowerCAmelCase__ ) a__ : List[Any] = np.shape(lowerCAmelCase__ ) if shape_a[0] != shape_b[0]: a__ : List[Any] = ( '''Expected the same number of rows for A and B. ''' F'Instead found A of size {shape_a} and B of size {shape_b}' ) raise ValueError(lowerCAmelCase__ ) if shape_b[1] != shape_c[1]: a__ : Optional[int] = ( '''Expected the same number of columns for B and C. ''' F'Instead found B of size {shape_b} and C of size {shape_c}' ) raise ValueError(lowerCAmelCase__ ) a__ : List[Any] = pseudo_inv if a_inv is None: try: a__ : int = np.linalg.inv(lowerCAmelCase__ ) except np.linalg.LinAlgError: raise ValueError( '''Input matrix A is not invertible. Cannot compute Schur complement.''' ) return mat_c - mat_b.T @ a_inv @ mat_b class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Any ) -> None: '''simple docstring''' a__ : int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) a__ : Union[str, Any] = np.array([[0, 3], [3, 0], [2, 3]] ) a__ : List[str] = np.array([[2, 1], [6, 3]] ) a__ : int = schur_complement(A__ , A__ , A__ ) a__ : List[str] = np.block([[a, b], [b.T, c]] ) a__ : Tuple = np.linalg.det(A__ ) a__ : Dict = np.linalg.det(A__ ) a__ : List[str] = np.linalg.det(A__ ) self.assertAlmostEqual(A__ , det_a * det_s ) def __lowerCAmelCase ( self : Union[str, Any] ) -> None: '''simple docstring''' a__ : List[str] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) a__ : int = np.array([[0, 3], [3, 0], [2, 3]] ) a__ : Tuple = np.array([[2, 1], [6, 3]] ) with self.assertRaises(A__ ): schur_complement(A__ , A__ , A__ ) def __lowerCAmelCase ( self : Tuple ) -> None: '''simple docstring''' a__ : Tuple = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) a__ : List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) a__ : Any = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(A__ ): schur_complement(A__ , A__ , A__ ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
688
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
1
'''simple docstring''' import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def _a ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Path , _SCREAMING_SNAKE_CASE : str = None , _SCREAMING_SNAKE_CASE : str = None , _SCREAMING_SNAKE_CASE : str = None , ): if config_name_or_path is None: _SCREAMING_SNAKE_CASE = "facebook/rag-token-base" if model_type == "rag_token" else "facebook/rag-sequence-base" if generator_tokenizer_name_or_path is None: _SCREAMING_SNAKE_CASE = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: _SCREAMING_SNAKE_CASE = question_encoder_name_or_path _SCREAMING_SNAKE_CASE = RagTokenForGeneration if model_type == "rag_token" else RagSequenceForGeneration # Save model. _SCREAMING_SNAKE_CASE = RagConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE = gen_config _SCREAMING_SNAKE_CASE = question_encoder_config _SCREAMING_SNAKE_CASE = model_class.from_pretrained_question_encoder_generator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE ) rag_model.save_pretrained(_SCREAMING_SNAKE_CASE ) # Sanity check. model_class.from_pretrained(_SCREAMING_SNAKE_CASE ) # Save tokenizers. _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) gen_tokenizer.save_pretrained(dest_dir / "generator_tokenizer/" ) _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) question_encoder_tokenizer.save_pretrained(dest_dir / "question_encoder_tokenizer/" ) if __name__ == "__main__": _snake_case : Any = argparse.ArgumentParser() parser.add_argument( """--model_type""", choices=["""rag_sequence""", """rag_token"""], required=True, type=str, help="""RAG model type: rag_sequence, rag_token""", ) parser.add_argument("""--dest""", type=str, required=True, help="""Path to the output checkpoint directory.""") parser.add_argument("""--generator_name_or_path""", type=str, required=True, help="""Generator model identifier""") parser.add_argument( """--question_encoder_name_or_path""", type=str, required=True, help="""Question encoder model identifier""" ) parser.add_argument( """--generator_tokenizer_name_or_path""", type=str, help="""Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``""", ) parser.add_argument( """--question_encoder_tokenizer_name_or_path""", type=str, help="""Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``""", ) parser.add_argument( """--config_name_or_path""", type=str, help=( """Identifier of the model config to use, if not provided, resolves to a base config for a given""" """ ``model_type``""" ), ) _snake_case : List[str] = parser.parse_args() _snake_case : int = Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
493
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _snake_case : Optional[Any] = { """configuration_rag""": ["""RagConfig"""], """retrieval_rag""": ["""RagRetriever"""], """tokenization_rag""": ["""RagTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ """RagModel""", """RagPreTrainedModel""", """RagSequenceForGeneration""", """RagTokenForGeneration""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Dict = [ """TFRagModel""", """TFRagPreTrainedModel""", """TFRagSequenceForGeneration""", """TFRagTokenForGeneration""", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
493
1
'''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 __magic_name__ ( _A ): UpperCAmelCase ="char" UpperCAmelCase ="bpe" UpperCAmelCase ="wp" lowercase =(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __magic_name__ ( _A ): UpperCAmelCase =["image_processor", "char_tokenizer"] UpperCAmelCase ="ViTImageProcessor" UpperCAmelCase ="MgpstrTokenizer" def __init__( self , snake_case=None , snake_case=None , **snake_case) -> Any: '''simple docstring''' _UpperCAmelCase : Dict =None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , snake_case , ) _UpperCAmelCase : int =kwargs.pop('feature_extractor') _UpperCAmelCase : int =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`.') _UpperCAmelCase : Union[str, Any] =tokenizer _UpperCAmelCase : Any =AutoTokenizer.from_pretrained('gpt2') _UpperCAmelCase : str =AutoTokenizer.from_pretrained('bert-base-uncased') super().__init__(snake_case , snake_case) def __call__( self , snake_case=None , snake_case=None , snake_case=None , **snake_case) -> Dict: '''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: _UpperCAmelCase : Tuple =self.image_processor(snake_case , return_tensors=snake_case , **snake_case) if text is not None: _UpperCAmelCase : Optional[Any] =self.char_tokenizer(snake_case , return_tensors=snake_case , **snake_case) if text is None: return inputs elif images is None: return encodings else: _UpperCAmelCase : str =encodings["input_ids"] return inputs def lowerCAmelCase ( self , snake_case) -> List[str]: '''simple docstring''' _UpperCAmelCase : int =sequences _UpperCAmelCase : int =char_preds.size(0) _UpperCAmelCase : Dict =self._decode_helper(snake_case , 'char') _UpperCAmelCase : List[str] =self._decode_helper(snake_case , 'bpe') _UpperCAmelCase : List[Any] =self._decode_helper(snake_case , 'wp') _UpperCAmelCase : Any =[] _UpperCAmelCase : Optional[int] =[] for i in range(snake_case): _UpperCAmelCase : Any =[char_scores[i], bpe_scores[i], wp_scores[i]] _UpperCAmelCase : Tuple =[char_strs[i], bpe_strs[i], wp_strs[i]] _UpperCAmelCase : Dict =scores.index(max(snake_case)) final_strs.append(strs[max_score_index]) final_scores.append(scores[max_score_index]) _UpperCAmelCase : Optional[int] ={} _UpperCAmelCase : List[str] =final_strs _UpperCAmelCase : Union[str, Any] =final_scores _UpperCAmelCase : Union[str, Any] =char_strs _UpperCAmelCase : Optional[Any] =bpe_strs _UpperCAmelCase : Union[str, Any] =wp_strs return out def lowerCAmelCase ( self , snake_case , snake_case) -> Optional[int]: '''simple docstring''' if format == DecodeType.CHARACTER: _UpperCAmelCase : Dict =self.char_decode _UpperCAmelCase : Dict =1 _UpperCAmelCase : List[Any] ="[s]" elif format == DecodeType.BPE: _UpperCAmelCase : Optional[Any] =self.bpe_decode _UpperCAmelCase : Optional[Any] =2 _UpperCAmelCase : Dict ="#" elif format == DecodeType.WORDPIECE: _UpperCAmelCase : int =self.wp_decode _UpperCAmelCase : Union[str, Any] =1_0_2 _UpperCAmelCase : Optional[int] ="[SEP]" else: raise ValueError(f"Format {format} is not supported.") _UpperCAmelCase : List[str] =[], [] _UpperCAmelCase : List[str] =pred_logits.size(0) _UpperCAmelCase : Optional[int] =pred_logits.size(1) _UpperCAmelCase : Dict =pred_logits.topk(1 , dim=-1 , largest=snake_case , sorted=snake_case) _UpperCAmelCase : Optional[Any] =preds_index.view(-1 , snake_case)[:, 1:] _UpperCAmelCase : Optional[int] =decoder(snake_case) _UpperCAmelCase : List[Any] =torch.nn.functional.softmax(snake_case , dim=2).max(dim=2) _UpperCAmelCase : str =preds_max_prob[:, 1:] for index in range(snake_case): _UpperCAmelCase : Optional[Any] =preds_str[index].find(snake_case) _UpperCAmelCase : Tuple =preds_str[index][:pred_eos] _UpperCAmelCase : Dict =preds_index[index].cpu().tolist() _UpperCAmelCase : Dict =pred_index.index(snake_case) if eos_token in pred_index else -1 _UpperCAmelCase : str =preds_max_prob[index][: pred_eos_index + 1] _UpperCAmelCase : Union[str, Any] =pred_max_prob.cumprod(dim=0)[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(snake_case) conf_scores.append(snake_case) return dec_strs, conf_scores def lowerCAmelCase ( self , snake_case) -> int: '''simple docstring''' _UpperCAmelCase : str =[seq.replace(' ' , '') for seq in self.char_tokenizer.batch_decode(snake_case)] return decode_strs def lowerCAmelCase ( self , snake_case) -> Optional[Any]: '''simple docstring''' return self.bpe_tokenizer.batch_decode(snake_case) def lowerCAmelCase ( self , snake_case) -> Dict: '''simple docstring''' _UpperCAmelCase : Optional[int] =[seq.replace(' ' , '') for seq in self.wp_tokenizer.batch_decode(snake_case)] return decode_strs
446
from math import factorial, radians def lowercase_ ( __snake_case : float , __snake_case : int = 18 , __snake_case : int = 10 ) -> float: '''simple docstring''' snake_case__ :Optional[int] = angle_in_degrees - ((angle_in_degrees // 3_6_0.0) * 3_6_0.0) # Converting from degrees to radians snake_case__ :Optional[int] = radians(__snake_case ) snake_case__ :Optional[Any] = angle_in_radians snake_case__ :Optional[int] = 3 snake_case__ :Union[str, Any] = -1 for _ in range(__snake_case ): result += (b * (angle_in_radians**a)) / factorial(__snake_case ) snake_case__ :Optional[int] = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(__snake_case , __snake_case ) if __name__ == "__main__": __import__("doctest").testmod()
241
0
from __future__ import annotations def lowerCamelCase__ ( A__ : Optional[Any] , A__ : Union[str, Any] , A__ : Optional[int] , A__ : Optional[Any] ): # noqa: E741 '''simple docstring''' while r - l > 1: __lowerCamelCase = (l + r) // 2 if v[m] >= key: __lowerCamelCase = m else: __lowerCamelCase = m # noqa: E741 return r def lowerCamelCase__ ( A__ : int ): '''simple docstring''' if len(_lowercase ) == 0: return 0 __lowerCamelCase = [0] * len(_lowercase ) __lowerCamelCase = 1 __lowerCamelCase = v[0] for i in range(1 , len(_lowercase ) ): if v[i] < tail[0]: __lowerCamelCase = v[i] elif v[i] > tail[length - 1]: __lowerCamelCase = v[i] length += 1 else: __lowerCamelCase = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
718
import os from collections.abc import Iterator def lowerCamelCase__ ( A__ : str = "." ): '''simple docstring''' for dir_path, dir_names, filenames in os.walk(A__ ): __lowerCamelCase = [d for d in dir_names if d != """scripts""" and d[0] not in """._"""] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(A__ )[1] in (".py", ".ipynb"): yield os.path.join(A__ , A__ ).lstrip("""./""" ) def lowerCamelCase__ ( A__ : Optional[int] ): '''simple docstring''' return f'{i * " "}*' if i else "\n##" def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(A__ ) or old_parts[i] != new_part) and new_part: print(f'{md_prefix(A__ )} {new_part.replace("_" , " " ).title()}' ) return new_path def lowerCamelCase__ ( A__ : str = "." ): '''simple docstring''' __lowerCamelCase = """""" for filepath in sorted(good_file_paths(A__ ) ): __lowerCamelCase, __lowerCamelCase = os.path.split(A__ ) if filepath != old_path: __lowerCamelCase = print_path(A__ , A__ ) __lowerCamelCase = (filepath.count(os.sep ) + 1) if filepath else 0 __lowerCamelCase = f'{filepath}/{filename}'.replace(""" """ , """%20""" ) __lowerCamelCase = os.path.splitext(filename.replace("""_""" , """ """ ).title() )[0] print(f'{md_prefix(A__ )} [{filename}]({url})' ) if __name__ == "__main__": print_directory_md('.')
80
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a : Optional[int] = { "169M": 12, "430M": 24, "1B5": 24, "3B": 32, "7B": 32, "14B": 40, } a : Any = { "169M": 768, "430M": 1_024, "1B5": 2_048, "3B": 2_560, "7B": 4_096, "14B": 5_120, } def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] ): __UpperCAmelCase : Optional[Any] = list(state_dict.keys() ) for name in state_dict_keys: __UpperCAmelCase : Optional[int] = state_dict.pop(__lowerCamelCase ) # emb -> embedding if name.startswith("""emb.""" ): __UpperCAmelCase : Optional[int] = name.replace("""emb.""" , """embeddings.""" ) # ln_0 -> pre_ln (only present at block 0) if name.startswith("""blocks.0.ln0""" ): __UpperCAmelCase : Optional[int] = name.replace("""blocks.0.ln0""" , """blocks.0.pre_ln""" ) # att -> attention __UpperCAmelCase : Tuple = re.sub(R"""blocks\.(\d+)\.att""" , R"""blocks.\1.attention""" , __lowerCamelCase ) # ffn -> feed_forward __UpperCAmelCase : Tuple = re.sub(R"""blocks\.(\d+)\.ffn""" , R"""blocks.\1.feed_forward""" , __lowerCamelCase ) # time_mix_k -> time_mix_key and reshape if name.endswith(""".time_mix_k""" ): __UpperCAmelCase : Optional[Any] = name.replace(""".time_mix_k""" , """.time_mix_key""" ) # time_mix_v -> time_mix_value and reshape if name.endswith(""".time_mix_v""" ): __UpperCAmelCase : Any = name.replace(""".time_mix_v""" , """.time_mix_value""" ) # time_mix_r -> time_mix_key and reshape if name.endswith(""".time_mix_r""" ): __UpperCAmelCase : Dict = name.replace(""".time_mix_r""" , """.time_mix_receptance""" ) if name != "head.weight": __UpperCAmelCase : Union[str, Any] = """rwkv.""" + name __UpperCAmelCase : Tuple = weight return state_dict def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : Tuple=None ): # 1. If possible, build the tokenizer. if tokenizer_file is None: print("""No `--tokenizer_file` provided, we will use the default tokenizer.""" ) __UpperCAmelCase : Tuple = 50277 __UpperCAmelCase : Tuple = AutoTokenizer.from_pretrained("""EleutherAI/gpt-neox-20b""" ) else: __UpperCAmelCase : Any = PreTrainedTokenizerFast(tokenizer_file=__lowerCamelCase ) __UpperCAmelCase : List[str] = len(__lowerCamelCase ) tokenizer.save_pretrained(__lowerCamelCase ) # 2. Build the config __UpperCAmelCase : Union[str, Any] = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: __UpperCAmelCase : Optional[int] = candidate break if size is None: raise ValueError("""Could not infer the size, please provide it with the `--size` argument.""" ) if size not in possible_sizes: raise ValueError(f"""`size` should be one of {possible_sizes}, got {size}.""" ) __UpperCAmelCase : List[str] = RwkvConfig( vocab_size=__lowerCamelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(__lowerCamelCase ) # 3. Download model file then convert state_dict __UpperCAmelCase : Tuple = hf_hub_download(__lowerCamelCase , __lowerCamelCase ) __UpperCAmelCase : Dict = torch.load(__lowerCamelCase , map_location="""cpu""" ) __UpperCAmelCase : Dict = convert_state_dict(__lowerCamelCase ) # 4. Split in shards and save __UpperCAmelCase , __UpperCAmelCase : List[str] = shard_checkpoint(__lowerCamelCase ) for shard_file, shard in shards.items(): torch.save(__lowerCamelCase , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) if index is not None: __UpperCAmelCase : Optional[Any] = os.path.join(__lowerCamelCase , __lowerCamelCase ) # Save the index as well with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as f: __UpperCAmelCase : Dict = json.dumps(__lowerCamelCase , indent=2 , sort_keys=__lowerCamelCase ) + """\n""" f.write(__lowerCamelCase ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( """Cleaning up shards. This may error with an OOM error, it this is the case don't worry you still have converted the model.""" ) __UpperCAmelCase : List[str] = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: __UpperCAmelCase : Dict = torch.load(os.path.join(__lowerCamelCase , __lowerCamelCase ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError("""Please provide a `model_name` to push the model to the Hub.""" ) __UpperCAmelCase : Tuple = AutoModelForCausalLM.from_pretrained(__lowerCamelCase ) model.push_to_hub(__lowerCamelCase , max_shard_size="""2GB""" ) tokenizer.push_to_hub(__lowerCamelCase ) if __name__ == "__main__": a : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--repo_id", default=None, type=str, required=True, help="Repo ID from which to pull the checkpoint." ) parser.add_argument( "--checkpoint_file", default=None, type=str, required=True, help="Name of the checkpoint file in the repo." ) parser.add_argument( "--output_dir", default=None, type=str, required=True, help="Where to save the converted model." ) parser.add_argument( "--tokenizer_file", default=None, type=str, help="Path to the tokenizer file to use (if not provided, only the model is converted).", ) parser.add_argument( "--size", default=None, type=str, help="Size of the model. Will be inferred from the `checkpoint_file` if not passed.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Push to the Hub the converted model.", ) parser.add_argument( "--model_name", default=None, type=str, help="Name of the pushed model on the Hub, including the username / organization.", ) a : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
63
def UpperCamelCase( __UpperCamelCase : Any ): if not head: return True # split the list to two parts lowerCAmelCase_ , lowerCAmelCase_ : Any = head.next, head while fast and fast.next: lowerCAmelCase_ : List[Any] = fast.next.next lowerCAmelCase_ : Union[str, Any] = slow.next lowerCAmelCase_ : Union[str, Any] = slow.next lowerCAmelCase_ : List[Any] = None # Don't forget here! But forget still works! # reverse the second part lowerCAmelCase_ : str = None while second: lowerCAmelCase_ : List[str] = second.next lowerCAmelCase_ : List[Any] = node lowerCAmelCase_ : Tuple = second lowerCAmelCase_ : Optional[int] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False lowerCAmelCase_ : Union[str, Any] = node.next lowerCAmelCase_ : str = head.next return True def UpperCamelCase( __UpperCamelCase : str ): if not head or not head.next: return True # 1. Get the midpoint (slow) lowerCAmelCase_ : Any = head while fast and fast.next: lowerCAmelCase_ , lowerCAmelCase_ : List[str] = fast.next.next, slow.next # 2. Push the second half into the stack lowerCAmelCase_ : List[str] = [slow.val] while slow.next: lowerCAmelCase_ : List[str] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False lowerCAmelCase_ : Optional[int] = cur.next return True def UpperCamelCase( __UpperCamelCase : Any ): if not head or not head.next: return True lowerCAmelCase_ : Optional[int] = {} lowerCAmelCase_ : List[Any] = 0 while head: if head.val in d: d[head.val].append(__UpperCamelCase ) else: lowerCAmelCase_ : Tuple = [pos] lowerCAmelCase_ : Tuple = head.next pos += 1 lowerCAmelCase_ : int = pos - 1 lowerCAmelCase_ : int = 0 for v in d.values(): if len(__UpperCamelCase ) % 2 != 0: middle += 1 else: lowerCAmelCase_ : Any = 0 for i in range(0 ,len(__UpperCamelCase ) ): if v[i] + v[len(__UpperCamelCase ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
171
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
701
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ = """true""" def a__ ( _UpperCamelCase : Union[str, Any] ,_UpperCamelCase : List[str]=82 ,_UpperCamelCase : Optional[Any]=16 ): set_seed(42 ) __lowerCamelCase = RegressionModel() __lowerCamelCase = deepcopy(_UpperCamelCase ) __lowerCamelCase = RegressionDataset(length=_UpperCamelCase ) __lowerCamelCase = DataLoader(_UpperCamelCase ,batch_size=_UpperCamelCase ) model.to(accelerator.device ) __lowerCamelCase ,__lowerCamelCase = accelerator.prepare(_UpperCamelCase ,_UpperCamelCase ) return model, ddp_model, dataloader def a__ ( _UpperCamelCase : Accelerator ,_UpperCamelCase : str=False ): __lowerCamelCase = AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased''' ) __lowerCamelCase = load_dataset('''glue''' ,'''mrpc''' ,split='''validation''' ) def tokenize_function(_UpperCamelCase : int ): __lowerCamelCase = tokenizer(examples['''sentence1'''] ,examples['''sentence2'''] ,truncation=_UpperCamelCase ,max_length=_UpperCamelCase ) return outputs with accelerator.main_process_first(): __lowerCamelCase = dataset.map( _UpperCamelCase ,batched=_UpperCamelCase ,remove_columns=['''idx''', '''sentence1''', '''sentence2'''] ,) __lowerCamelCase = tokenized_datasets.rename_column('''label''' ,'''labels''' ) def collate_fn(_UpperCamelCase : Any ): if use_longest: return tokenizer.pad(_UpperCamelCase ,padding='''longest''' ,return_tensors='''pt''' ) return tokenizer.pad(_UpperCamelCase ,padding='''max_length''' ,max_length=1_28 ,return_tensors='''pt''' ) return DataLoader(_UpperCamelCase ,shuffle=_UpperCamelCase ,collate_fn=_UpperCamelCase ,batch_size=16 ) def a__ ( _UpperCamelCase : Dict ,_UpperCamelCase : List[str] ): __lowerCamelCase = Accelerator(dispatch_batches=_UpperCamelCase ,split_batches=_UpperCamelCase ) __lowerCamelCase = get_dataloader(_UpperCamelCase ,not dispatch_batches ) __lowerCamelCase = AutoModelForSequenceClassification.from_pretrained( '''hf-internal-testing/mrpc-bert-base-cased''' ,return_dict=_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = accelerator.prepare(_UpperCamelCase ,_UpperCamelCase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def a__ ( _UpperCamelCase : Dict ,_UpperCamelCase : Optional[Any] ,_UpperCamelCase : Union[str, Any] ): __lowerCamelCase = [] for batch in dataloader: __lowerCamelCase ,__lowerCamelCase = batch.values() with torch.no_grad(): __lowerCamelCase = model(_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) __lowerCamelCase ,__lowerCamelCase = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCamelCase ) targs.append(_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = torch.cat(_UpperCamelCase ), torch.cat(_UpperCamelCase ) return logits, targs def a__ ( _UpperCamelCase : Accelerator ,_UpperCamelCase : List[Any]=82 ,_UpperCamelCase : str=False ,_UpperCamelCase : List[str]=False ,_UpperCamelCase : Optional[int]=16 ): __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = get_basic_setup(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = generate_predictions(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) assert ( len(_UpperCamelCase ) == num_samples ), F"""Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCamelCase )}""" def a__ ( _UpperCamelCase : bool = False ,_UpperCamelCase : bool = False ): __lowerCamelCase = evaluate.load('''glue''' ,'''mrpc''' ) __lowerCamelCase ,__lowerCamelCase = get_mrpc_setup(_UpperCamelCase ,_UpperCamelCase ) # First do baseline __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = setup['''no'''] model.to(_UpperCamelCase ) model.eval() for batch in dataloader: batch.to(_UpperCamelCase ) with torch.inference_mode(): __lowerCamelCase = model(**_UpperCamelCase ) __lowerCamelCase = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=_UpperCamelCase ,references=batch['''labels'''] ) __lowerCamelCase = metric.compute() # Then do distributed __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = setup['''ddp'''] model.eval() for batch in dataloader: with torch.inference_mode(): __lowerCamelCase = model(**_UpperCamelCase ) __lowerCamelCase = outputs.logits.argmax(dim=-1 ) __lowerCamelCase = batch['''labels'''] __lowerCamelCase ,__lowerCamelCase = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=_UpperCamelCase ,references=_UpperCamelCase ) __lowerCamelCase = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] ,distributed[key] ), F"""Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n""" def a__ ( ): __lowerCamelCase = Accelerator(split_batches=_UpperCamelCase ,dispatch_batches=_UpperCamelCase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('''**Testing gather_for_metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`""" ) test_mrpc(_UpperCamelCase ,_UpperCamelCase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test torch metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: __lowerCamelCase = Accelerator(split_batches=_UpperCamelCase ,dispatch_batches=_UpperCamelCase ) if accelerator.is_local_main_process: print(F"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99""" ) test_torch_metrics(_UpperCamelCase ,99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test last batch is not dropped when perfectly divisible**''' ) __lowerCamelCase = Accelerator() test_torch_metrics(_UpperCamelCase ,5_12 ) accelerator.state._reset_state() def a__ ( _UpperCamelCase : Optional[int] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
622
0
from typing import Dict from .base import GenericTensor, Pipeline class snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple , lowerCAmelCase : List[Any]=None , lowerCAmelCase : int=None , lowerCAmelCase : int=None , **lowerCAmelCase : Tuple) -> Optional[int]: """simple docstring""" if tokenize_kwargs is None: _snake_case : Tuple = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""") _snake_case : str = truncation _snake_case : Dict = tokenize_kwargs _snake_case : List[Any] = {} if return_tensors is not None: _snake_case : int = return_tensors return preprocess_params, {}, postprocess_params def UpperCamelCase_ ( self : Tuple , lowerCAmelCase : Tuple , **lowerCAmelCase : Optional[Any]) -> Dict[str, GenericTensor]: """simple docstring""" _snake_case : int = self.framework _snake_case : Optional[Any] = self.tokenizer(lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase) return model_inputs def UpperCamelCase_ ( self : Any , lowerCAmelCase : List[str]) -> int: """simple docstring""" _snake_case : List[str] = self.model(**lowerCAmelCase) return model_outputs def UpperCamelCase_ ( self : List[str] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Any=False) -> Tuple: """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self : Dict , *lowerCAmelCase : str , **lowerCAmelCase : Any) -> Dict: """simple docstring""" return super().__call__(*lowerCAmelCase , **lowerCAmelCase)
477
import warnings 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 snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' snake_case_ : Optional[int] = ["""image_processor""", """tokenizer"""] snake_case_ : Optional[int] = """LayoutLMv2ImageProcessor""" snake_case_ : Dict = ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""") def __init__( self : Optional[int] , lowerCAmelCase : List[str]=None , lowerCAmelCase : List[Any]=None , **lowerCAmelCase : List[str]) -> Optional[Any]: """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowerCAmelCase , ) _snake_case : Tuple = kwargs.pop("""feature_extractor""") _snake_case : List[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(lowerCAmelCase , lowerCAmelCase) def __call__( self : List[str] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , lowerCAmelCase : Union[List[List[int]], List[List[List[int]]]] = None , lowerCAmelCase : Optional[Union[List[int], List[List[int]]]] = None , lowerCAmelCase : bool = True , lowerCAmelCase : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : int = 0 , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : Optional[bool] = None , lowerCAmelCase : Optional[bool] = None , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[Union[str, TensorType]] = None , **lowerCAmelCase : Optional[int] , ) -> BatchEncoding: """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( """You cannot provide bounding boxes """ """if you initialized the image processor with apply_ocr set to True.""") if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( """You cannot provide word labels if you initialized the image processor with apply_ocr set to True.""") if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("""You cannot return overflowing tokens without returning the offsets mapping.""") # first, apply the image processor _snake_case : str = self.image_processor(images=lowerCAmelCase , return_tensors=lowerCAmelCase) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(lowerCAmelCase , lowerCAmelCase): _snake_case : Optional[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension) _snake_case : Optional[Any] = features["""words"""] _snake_case : Tuple = self.tokenizer( text=text if text is not None else features["""words"""] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["""boxes"""] , word_labels=lowerCAmelCase , add_special_tokens=lowerCAmelCase , padding=lowerCAmelCase , truncation=lowerCAmelCase , max_length=lowerCAmelCase , stride=lowerCAmelCase , pad_to_multiple_of=lowerCAmelCase , return_token_type_ids=lowerCAmelCase , return_attention_mask=lowerCAmelCase , return_overflowing_tokens=lowerCAmelCase , return_special_tokens_mask=lowerCAmelCase , return_offsets_mapping=lowerCAmelCase , return_length=lowerCAmelCase , verbose=lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase , ) # add pixel values _snake_case : Optional[int] = features.pop("""pixel_values""") if return_overflowing_tokens is True: _snake_case : Tuple = self.get_overflowing_images(lowerCAmelCase , encoded_inputs["""overflow_to_sample_mapping"""]) _snake_case : int = images return encoded_inputs def UpperCamelCase_ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Tuple) -> Tuple: """simple docstring""" _snake_case : int = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx]) if len(lowerCAmelCase) != len(lowerCAmelCase): raise ValueError( """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got""" F''' {len(lowerCAmelCase)} and {len(lowerCAmelCase)}''') return images_with_overflow def UpperCamelCase_ ( self : List[Any] , *lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : Optional[int]) -> int: """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase , **lowerCAmelCase) def UpperCamelCase_ ( self : Dict , *lowerCAmelCase : Any , **lowerCAmelCase : int) -> List[str]: """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase , **lowerCAmelCase) @property def UpperCamelCase_ ( self : Tuple) -> Any: """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase_ ( self : Any) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , lowerCAmelCase , ) return self.image_processor_class @property def UpperCamelCase_ ( self : Optional[int]) -> List[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , lowerCAmelCase , ) return self.image_processor
477
1
class __snake_case : def __init__( self : List[Any] ) -> str: '''simple docstring''' _lowerCAmelCase : str = {} def SCREAMING_SNAKE_CASE ( self : Dict ) -> None: '''simple docstring''' print(self.vertex ) for i in self.vertex: print(_UpperCAmelCase , """ -> """ , """ -> """.join([str(_UpperCAmelCase ) for j in self.vertex[i]] ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> None: '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(_UpperCAmelCase ) else: # else make a new vertex _lowerCAmelCase : Optional[int] = [to_vertex] def SCREAMING_SNAKE_CASE ( self : Dict ) -> None: '''simple docstring''' _lowerCAmelCase : int = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(_UpperCAmelCase , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , _UpperCAmelCase : int , _UpperCAmelCase : list ) -> None: '''simple docstring''' _lowerCAmelCase : List[str] = True print(_UpperCAmelCase , end=""" """ ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("DFS:") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
196
from __future__ import annotations from collections.abc import Iterator from typing import Any class __snake_case : def __init__( self : List[Any] , _UpperCAmelCase : Any ) -> Dict: '''simple docstring''' _lowerCAmelCase : Any = data _lowerCAmelCase : Node | None = None class __snake_case : def __init__( self : Tuple ) -> Tuple: '''simple docstring''' _lowerCAmelCase : str = None _lowerCAmelCase : List[Any] = None def __iter__( self : str ) -> Iterator[Any]: '''simple docstring''' _lowerCAmelCase : Optional[int] = self.head while self.head: yield node.data _lowerCAmelCase : List[str] = node.next if node == self.head: break def __len__( self : Union[str, Any] ) -> int: '''simple docstring''' return sum(1 for _ in self ) def __repr__( self : Optional[int] ) -> str: '''simple docstring''' return "->".join(str(_UpperCAmelCase ) for item in iter(self ) ) def SCREAMING_SNAKE_CASE ( self : Any , _UpperCAmelCase : Any ) -> None: '''simple docstring''' self.insert_nth(len(self ) , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict , _UpperCAmelCase : Any ) -> None: '''simple docstring''' self.insert_nth(0 , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] , _UpperCAmelCase : int , _UpperCAmelCase : Any ) -> None: '''simple docstring''' if index < 0 or index > len(self ): raise IndexError("""list index out of range.""" ) _lowerCAmelCase : Optional[int] = Node(_UpperCAmelCase ) if self.head is None: _lowerCAmelCase : Tuple = new_node # first node points itself _lowerCAmelCase : int = new_node elif index == 0: # insert at head _lowerCAmelCase : Tuple = self.head _lowerCAmelCase : int = new_node else: _lowerCAmelCase : Union[str, Any] = self.head for _ in range(index - 1 ): _lowerCAmelCase : Optional[Any] = temp.next _lowerCAmelCase : Optional[int] = temp.next _lowerCAmelCase : Optional[int] = new_node if index == len(self ) - 1: # insert at tail _lowerCAmelCase : Optional[Any] = new_node def SCREAMING_SNAKE_CASE ( self : Dict ) -> str: '''simple docstring''' return self.delete_nth(0 ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def SCREAMING_SNAKE_CASE ( self : str , _UpperCAmelCase : int = 0 ) -> Any: '''simple docstring''' if not 0 <= index < len(self ): raise IndexError("""list index out of range.""" ) _lowerCAmelCase : Optional[Any] = self.head if self.head == self.tail: # just one node _lowerCAmelCase : Optional[Any] = None elif index == 0: # delete head node _lowerCAmelCase : str = self.tail.next.next _lowerCAmelCase : List[str] = self.head.next else: _lowerCAmelCase : List[str] = self.head for _ in range(index - 1 ): _lowerCAmelCase : List[Any] = temp.next _lowerCAmelCase : List[str] = temp.next _lowerCAmelCase : Dict = temp.next.next if index == len(self ) - 1: # delete at tail _lowerCAmelCase : Optional[int] = temp return delete_node.data def SCREAMING_SNAKE_CASE ( self : int ) -> bool: '''simple docstring''' return len(self ) == 0 def _UpperCAmelCase (): '''simple docstring''' _lowerCAmelCase : Dict = CircularLinkedList() assert len(UpperCamelCase_ ) == 0 assert circular_linked_list.is_empty() is True assert str(UpperCamelCase_ ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(UpperCamelCase_ ) == i circular_linked_list.insert_nth(UpperCamelCase_ , i + 1 ) assert str(UpperCamelCase_ ) == "->".join(str(UpperCamelCase_ ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(UpperCamelCase_ ) == "->".join(str(UpperCamelCase_ ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(UpperCamelCase_ ) == "->".join(str(UpperCamelCase_ ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(UpperCamelCase_ ) == "->".join(str(UpperCamelCase_ ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(UpperCamelCase_ ) == "->".join(str(UpperCamelCase_ ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
196
1
"""simple docstring""" from ...processing_utils import ProcessorMixin class _UpperCAmelCase ( __a): __a : List[str] = """WhisperFeatureExtractor""" __a : Optional[Any] = """WhisperTokenizer""" def __init__( self , _A , _A ) -> int: '''simple docstring''' super().__init__(_A , _A ) _UpperCAmelCase : Optional[int] = self.feature_extractor _UpperCAmelCase : Optional[Any] = False def __snake_case ( self , _A=None , _A=None , _A=True ) -> List[Any]: '''simple docstring''' return self.tokenizer.get_decoder_prompt_ids(task=_A , language=_A , no_timestamps=_A ) def __call__( self , *_A , **_A ) -> List[Any]: '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*_A , **_A ) _UpperCAmelCase : Dict = kwargs.pop("""audio""" , _A ) _UpperCAmelCase : Dict = kwargs.pop("""sampling_rate""" , _A ) _UpperCAmelCase : str = kwargs.pop("""text""" , _A ) if len(_A ) > 0: _UpperCAmelCase : Any = args[0] _UpperCAmelCase : Optional[int] = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: _UpperCAmelCase : int = self.feature_extractor(_A , *_A , sampling_rate=_A , **_A ) if text is not None: _UpperCAmelCase : Optional[int] = self.tokenizer(_A , **_A ) if text is None: return inputs elif audio is None: return encodings else: _UpperCAmelCase : Optional[int] = encodings["""input_ids"""] return inputs def __snake_case ( self , *_A , **_A ) -> Optional[int]: '''simple docstring''' return self.tokenizer.batch_decode(*_A , **_A ) def __snake_case ( self , *_A , **_A ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.decode(*_A , **_A ) def __snake_case ( self , _A , _A="np" ) -> Tuple: '''simple docstring''' return self.tokenizer.get_prompt_ids(_A , return_tensors=_A )
238
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') lowerCamelCase__ : str = logging.getLogger(__name__) @dataclass class _UpperCAmelCase : __a : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) __a : Optional[str] = field( default=__a , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) __a : Optional[str] = field( default=__a , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) __a : Optional[str] = field( default=__a , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) __a : bool = field( default=__a , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) __a : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) __a : bool = field( default=__a , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) @dataclass class _UpperCAmelCase : __a : Optional[str] = field(default=__a , metadata={"""help""": """The input training data file (a text file)."""}) __a : Optional[str] = field( default=__a , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , ) __a : bool = field( default=__a , metadata={"""help""": """Overwrite the cached training and evaluation sets"""}) __a : Optional[int] = field( default=__a , metadata={"""help""": """The number of processes to use for the preprocessing."""} , ) __a : Optional[int] = field( default=__a , metadata={ """help""": ( """The maximum total input sequence length after tokenization. If passed, sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __a : bool = field( default=__a , metadata={ """help""": ( """Whether to pad all samples to the maximum sentence length. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch. More """ """efficient on GPU but very bad for TPU.""" ) } , ) __a : Optional[int] = field( default=__a , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) __a : Optional[int] = field( default=__a , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def __snake_case ( self ) -> Union[str, Any]: '''simple docstring''' if self.train_file is not None: _UpperCAmelCase : Any = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: _UpperCAmelCase : int = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class _UpperCAmelCase : __a : PreTrainedTokenizerBase __a : Union[bool, str, PaddingStrategy] = True __a : Optional[int] = None __a : Optional[int] = None def __call__( self , _A ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : Union[str, Any] = """label""" if """label""" in features[0].keys() else """labels""" _UpperCAmelCase : Any = [feature.pop(_A ) for feature in features] _UpperCAmelCase : Optional[int] = len(_A ) _UpperCAmelCase : Union[str, Any] = len(features[0]["""input_ids"""] ) _UpperCAmelCase : str = [ [{k: v[i] for k, v in feature.items()} for i in range(_A )] for feature in features ] _UpperCAmelCase : List[str] = list(chain(*_A ) ) _UpperCAmelCase : int = self.tokenizer.pad( _A , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" , ) # Un-flatten _UpperCAmelCase : Optional[int] = {k: v.view(_A , _A , -1 ) for k, v in batch.items()} # Add back labels _UpperCAmelCase : Any = torch.tensor(_A , dtype=torch.intaa ) return batch def UpperCamelCase ( ) -> Dict: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _UpperCAmelCase : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : List[str] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_swag""", _lowerCAmelCase, _lowerCAmelCase ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", handlers=[logging.StreamHandler(sys.stdout )], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _UpperCAmelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(_lowerCAmelCase ) datasets.utils.logging.set_verbosity(_lowerCAmelCase ) transformers.utils.logging.set_verbosity(_lowerCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. _UpperCAmelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _UpperCAmelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: _UpperCAmelCase : Dict = {} if data_args.train_file is not None: _UpperCAmelCase : Optional[int] = data_args.train_file if data_args.validation_file is not None: _UpperCAmelCase : Optional[int] = data_args.validation_file _UpperCAmelCase : int = data_args.train_file.split(""".""" )[-1] _UpperCAmelCase : List[Any] = load_dataset( _lowerCAmelCase, data_files=_lowerCAmelCase, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) else: # Downloading and loading the swag dataset from the hub. _UpperCAmelCase : List[str] = load_dataset( """swag""", """regular""", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCAmelCase : Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) _UpperCAmelCase : Any = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) _UpperCAmelCase : List[str] = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool(""".ckpt""" in model_args.model_name_or_path ), config=_lowerCAmelCase, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # When using your own dataset or a different dataset from swag, you will probably need to change this. _UpperCAmelCase : str = [f'''ending{i}''' for i in range(4 )] _UpperCAmelCase : List[Any] = """sent1""" _UpperCAmelCase : str = """sent2""" if data_args.max_seq_length is None: _UpperCAmelCase : Tuple = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( """The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value""" """ of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can""" """ override this default with `--block_size xxx`.""" ) _UpperCAmelCase : List[str] = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the''' f'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' ) _UpperCAmelCase : Tuple = min(data_args.max_seq_length, tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(_lowerCAmelCase : str ): _UpperCAmelCase : int = [[context] * 4 for context in examples[context_name]] _UpperCAmelCase : List[Any] = examples[question_header_name] _UpperCAmelCase : List[str] = [ [f'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(_lowerCAmelCase ) ] # Flatten out _UpperCAmelCase : Any = list(chain(*_lowerCAmelCase ) ) _UpperCAmelCase : Any = list(chain(*_lowerCAmelCase ) ) # Tokenize _UpperCAmelCase : Dict = tokenizer( _lowerCAmelCase, _lowerCAmelCase, truncation=_lowerCAmelCase, max_length=_lowerCAmelCase, padding="""max_length""" if data_args.pad_to_max_length else False, ) # Un-flatten return {k: [v[i : i + 4] for i in range(0, len(_lowerCAmelCase ), 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("""--do_train requires a train dataset""" ) _UpperCAmelCase : Any = raw_datasets["""train"""] if data_args.max_train_samples is not None: _UpperCAmelCase : List[Any] = min(len(_lowerCAmelCase ), data_args.max_train_samples ) _UpperCAmelCase : List[Any] = train_dataset.select(range(_lowerCAmelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): _UpperCAmelCase : List[Any] = train_dataset.map( _lowerCAmelCase, batched=_lowerCAmelCase, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("""--do_eval requires a validation dataset""" ) _UpperCAmelCase : Optional[Any] = raw_datasets["""validation"""] if data_args.max_eval_samples is not None: _UpperCAmelCase : int = min(len(_lowerCAmelCase ), data_args.max_eval_samples ) _UpperCAmelCase : List[str] = eval_dataset.select(range(_lowerCAmelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): _UpperCAmelCase : List[str] = eval_dataset.map( _lowerCAmelCase, batched=_lowerCAmelCase, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, ) # Data collator _UpperCAmelCase : List[Any] = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=_lowerCAmelCase, pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(_lowerCAmelCase : List[Any] ): _UpperCAmelCase , _UpperCAmelCase : Optional[Any] = eval_predictions _UpperCAmelCase : Dict = np.argmax(_lowerCAmelCase, axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer _UpperCAmelCase : Union[str, Any] = Trainer( model=_lowerCAmelCase, args=_lowerCAmelCase, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=_lowerCAmelCase, data_collator=_lowerCAmelCase, compute_metrics=_lowerCAmelCase, ) # Training if training_args.do_train: _UpperCAmelCase : Dict = None if training_args.resume_from_checkpoint is not None: _UpperCAmelCase : Optional[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _UpperCAmelCase : int = last_checkpoint _UpperCAmelCase : Union[str, Any] = trainer.train(resume_from_checkpoint=_lowerCAmelCase ) trainer.save_model() # Saves the tokenizer too for easy upload _UpperCAmelCase : List[Any] = train_result.metrics _UpperCAmelCase : Dict = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowerCAmelCase ) ) _UpperCAmelCase : List[Any] = min(_lowerCAmelCase, len(_lowerCAmelCase ) ) trainer.log_metrics("""train""", _lowerCAmelCase ) trainer.save_metrics("""train""", _lowerCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _UpperCAmelCase : Optional[Any] = trainer.evaluate() _UpperCAmelCase : List[str] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_lowerCAmelCase ) _UpperCAmelCase : Optional[int] = min(_lowerCAmelCase, len(_lowerCAmelCase ) ) trainer.log_metrics("""eval""", _lowerCAmelCase ) trainer.save_metrics("""eval""", _lowerCAmelCase ) _UpperCAmelCase : int = { """finetuned_from""": model_args.model_name_or_path, """tasks""": """multiple-choice""", """dataset_tags""": """swag""", """dataset_args""": """regular""", """dataset""": """SWAG""", """language""": """en""", } if training_args.push_to_hub: trainer.push_to_hub(**_lowerCAmelCase ) else: trainer.create_model_card(**_lowerCAmelCase ) def UpperCamelCase ( _lowerCAmelCase : Tuple ) -> Tuple: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
238
1
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase : List[str] = logging.get_logger(__name__) _UpperCamelCase : Any = { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json""", } class _lowerCAmelCase( SCREAMING_SNAKE_CASE__): """simple docstring""" lowerCamelCase__ = '''mvp''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , UpperCAmelCase=5_02_67 , UpperCAmelCase=10_24 , UpperCAmelCase=12 , UpperCAmelCase=40_96 , UpperCAmelCase=16 , UpperCAmelCase=12 , UpperCAmelCase=40_96 , UpperCAmelCase=16 , UpperCAmelCase=0.0 , UpperCAmelCase=0.0 , UpperCAmelCase="gelu" , UpperCAmelCase=10_24 , UpperCAmelCase=0.1 , UpperCAmelCase=0.0 , UpperCAmelCase=0.0 , UpperCAmelCase=0.02 , UpperCAmelCase=0.0 , UpperCAmelCase=False , UpperCAmelCase=True , UpperCAmelCase=1 , UpperCAmelCase=0 , UpperCAmelCase=2 , UpperCAmelCase=True , UpperCAmelCase=2 , UpperCAmelCase=2 , UpperCAmelCase=False , UpperCAmelCase=1_00 , UpperCAmelCase=8_00 , **UpperCAmelCase , )-> Optional[int]: __A = vocab_size __A = max_position_embeddings __A = d_model __A = encoder_ffn_dim __A = encoder_layers __A = encoder_attention_heads __A = decoder_ffn_dim __A = decoder_layers __A = decoder_attention_heads __A = dropout __A = attention_dropout __A = activation_dropout __A = activation_function __A = init_std __A = encoder_layerdrop __A = decoder_layerdrop __A = classifier_dropout __A = use_cache __A = encoder_layers __A = scale_embedding # scale factor will be sqrt(d_model) if True __A = use_prompt __A = prompt_length __A = prompt_mid_dim super().__init__( pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , is_encoder_decoder=snake_case__ , decoder_start_token_id=snake_case__ , forced_eos_token_id=snake_case__ , **snake_case__ , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , snake_case__ ): __A = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " '''The config can simply be saved and uploaded again to be fixed.''' )
719
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version _UpperCamelCase : str = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.14.0""", """To fix: pip install -r examples/pytorch/audio-classification/requirements.txt""") def __UpperCamelCase ( snake_case , snake_case , snake_case = 1_6_0_0_0 ) -> Tuple: '''simple docstring''' __A = int(round(sample_rate * max_length ) ) if len(snake_case ) <= sample_length: return wav __A = randint(0 , len(snake_case ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class _lowerCAmelCase: """simple docstring""" lowerCamelCase__ = field(default=_a , metadata={'''help''': '''Name of a dataset from the datasets package'''}) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''A file containing the training audio paths and labels.'''}) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''A file containing the validation audio paths and labels.'''}) lowerCamelCase__ = field( default='''train''' , metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' } , ) lowerCamelCase__ = field( default='''validation''' , metadata={ '''help''': ( '''The name of the training data set split to use (via the datasets library). Defaults to \'validation\'''' ) } , ) lowerCamelCase__ = field( default='''audio''' , metadata={'''help''': '''The name of the dataset column containing the audio data. Defaults to \'audio\''''} , ) lowerCamelCase__ = field( default='''label''' , metadata={'''help''': '''The name of the dataset column containing the labels. Defaults to \'label\''''}) lowerCamelCase__ = field( default=_a , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) lowerCamelCase__ = field( default=_a , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) lowerCamelCase__ = field( default=20 , metadata={'''help''': '''Audio clips will be randomly cut to this length during training if the value is set.'''} , ) @dataclass class _lowerCAmelCase: """simple docstring""" lowerCamelCase__ = field( default='''facebook/wav2vec2-base''' , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} , ) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from the Hub'''}) lowerCamelCase__ = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''Name or path of preprocessor config.'''}) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''Whether to freeze the feature encoder layers of the model.'''}) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''Whether to generate an attention mask in the feature extractor.'''}) lowerCamelCase__ = field( default=_a , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}) lowerCamelCase__ = field( default=_a , metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''} , ) def SCREAMING_SNAKE_CASE__ ( self )-> List[str]: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''will be removed in a future version. Use `--freeze_feature_encoder`''' '''instead. Setting `freeze_feature_encoder==True`.''' , UpperCAmelCase , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''should not be used in combination with `--freeze_feature_encoder`.''' '''Only make use of `--freeze_feature_encoder`.''' ) def __UpperCamelCase ( ) -> Union[str, Any]: '''simple docstring''' __A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __A , __A , __A = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __A , __A , __A = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_audio_classification''' , snake_case , snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __A = training_args.get_process_log_level() logger.setLevel(snake_case ) transformers.utils.logging.set_verbosity(snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} " + F"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(F"Training/evaluation parameters {training_args}" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. __A = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __A = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. " '''Use --overwrite_output_dir to train from scratch.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset and prepare it for the audio classification task. __A = DatasetDict() __A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) __A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--audio_column_name` to the correct audio column - one of ''' F"{', '.join(raw_datasets['train'].column_names )}." ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--label_column_name` to the correct text column - one of ''' F"{', '.join(raw_datasets['train'].column_names )}." ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy __A = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. __A = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) __A = feature_extractor.model_input_names[0] def train_transforms(snake_case ): __A = [] for audio in batch[data_args.audio_column_name]: __A = random_subsample( audio['''array'''] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(snake_case ) __A = feature_extractor(snake_case , sampling_rate=feature_extractor.sampling_rate ) __A = {model_input_name: inputs.get(snake_case )} __A = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(snake_case ): __A = [audio['''array'''] for audio in batch[data_args.audio_column_name]] __A = feature_extractor(snake_case , sampling_rate=feature_extractor.sampling_rate ) __A = {model_input_name: inputs.get(snake_case )} __A = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. __A = raw_datasets['''train'''].features[data_args.label_column_name].names __A , __A = {}, {} for i, label in enumerate(snake_case ): __A = str(snake_case ) __A = label # Load the accuracy metric from the datasets package __A = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(snake_case ): __A = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=snake_case , references=eval_pred.label_ids ) __A = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(snake_case ) , labelaid=snake_case , idalabel=snake_case , finetuning_task='''audio-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __A = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: __A = ( raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(snake_case , output_all_columns=snake_case ) if training_args.do_eval: if data_args.max_eval_samples is not None: __A = ( raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(snake_case , output_all_columns=snake_case ) # Initialize our trainer __A = Trainer( model=snake_case , args=snake_case , train_dataset=raw_datasets['''train'''] if training_args.do_train else None , eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None , compute_metrics=snake_case , tokenizer=snake_case , ) # Training if training_args.do_train: __A = None if training_args.resume_from_checkpoint is not None: __A = training_args.resume_from_checkpoint elif last_checkpoint is not None: __A = last_checkpoint __A = trainer.train(resume_from_checkpoint=snake_case ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __A = trainer.evaluate() trainer.log_metrics('''eval''' , snake_case ) trainer.save_metrics('''eval''' , snake_case ) # Write model card and (optionally) push to hub __A = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''audio-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''audio-classification'''], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case ) else: trainer.create_model_card(**snake_case ) if __name__ == "__main__": main()
341
0
'''simple docstring''' import argparse from collections import defaultdict import yaml __A ='docs/source/en/_toctree.yml' def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : Dict = defaultdict(UpperCamelCase__ ) UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : Union[str, Any] = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({"""local""": doc["""local"""], """title""": doc["""title"""]} ) else: new_doc_list.append(UpperCamelCase__ ) UpperCAmelCase__ : int = new_doc_list UpperCAmelCase__ : List[str] = [key for key, value in counts.items() if value > 1] UpperCAmelCase__ : Any = [] for duplicate_key in duplicates: UpperCAmelCase__ : Union[str, Any] = list({doc["""title"""] for doc in doc_list if doc["""local"""] == duplicate_key} ) if len(UpperCamelCase__ ) > 1: raise ValueError( f'''{duplicate_key} is present several times in the documentation table of content at ''' """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if """local""" not in counts or counts[doc["""local"""]] == 1] ) UpperCAmelCase__ : Optional[int] = sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : s["title"].lower() ) # "overview" gets special treatment and is always first if len(UpperCamelCase__ ) > 1: raise ValueError("""{doc_list} has two 'overview' docs which is not allowed.""" ) overview_doc.extend(UpperCamelCase__ ) # Sort return overview_doc def _UpperCamelCase ( UpperCamelCase__=False ): with open(UpperCamelCase__ , encoding="""utf-8""" ) as f: UpperCAmelCase__ : Dict = yaml.safe_load(f.read() ) # Get to the API doc UpperCAmelCase__ : Any = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCAmelCase__ : Union[str, Any] = content[api_idx]["""sections"""] # Then to the model doc UpperCAmelCase__ : Any = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 UpperCAmelCase__ : Any = api_doc[scheduler_idx]["""sections"""] UpperCAmelCase__ : Union[str, Any] = clean_doc_toc(UpperCamelCase__ ) UpperCAmelCase__ : Union[str, Any] = False if new_scheduler_doc != scheduler_doc: UpperCAmelCase__ : int = True if overwrite: UpperCAmelCase__ : Union[str, Any] = new_scheduler_doc if diff: if overwrite: UpperCAmelCase__ : str = api_doc with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) def _UpperCamelCase ( UpperCamelCase__=False ): with open(UpperCamelCase__ , encoding="""utf-8""" ) as f: UpperCAmelCase__ : Any = yaml.safe_load(f.read() ) # Get to the API doc UpperCAmelCase__ : Tuple = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCAmelCase__ : List[Any] = content[api_idx]["""sections"""] # Then to the model doc UpperCAmelCase__ : int = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Optional[int] = api_doc[pipeline_idx]["""sections"""] UpperCAmelCase__ : Dict = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: UpperCAmelCase__ : Dict = pipeline_doc["""section"""] UpperCAmelCase__ : Optional[int] = clean_doc_toc(UpperCamelCase__ ) if overwrite: UpperCAmelCase__ : int = new_sub_pipeline_doc new_pipeline_docs.append(UpperCamelCase__ ) # sort overall pipeline doc UpperCAmelCase__ : Union[str, Any] = clean_doc_toc(UpperCamelCase__ ) if new_pipeline_docs != pipeline_docs: UpperCAmelCase__ : List[Any] = True if overwrite: UpperCAmelCase__ : int = new_pipeline_docs if diff: if overwrite: UpperCAmelCase__ : Dict = api_doc with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": __A =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A =parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
407
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed __A ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def _UpperCamelCase ( UpperCamelCase__ ): assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): if args.student_type == "roberta": UpperCAmelCase__ : Optional[Any] = False elif args.student_type == "gpt2": UpperCAmelCase__ : str = False def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): if args.student_type == "roberta": UpperCAmelCase__ : str = False def _UpperCamelCase ( ): UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=UpperCamelCase__ , choices=["""distilbert""", """roberta""", """gpt2"""] , required=UpperCamelCase__ , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=UpperCamelCase__ , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=UpperCamelCase__ , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=UpperCamelCase__ , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=UpperCamelCase__ , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=UpperCamelCase__ , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=UpperCamelCase__ , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=UpperCamelCase__ , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=UpperCamelCase__ , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=UpperCamelCase__ , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=UpperCamelCase__ , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=UpperCamelCase__ , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=UpperCamelCase__ , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=UpperCamelCase__ , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=UpperCamelCase__ , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=UpperCamelCase__ , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=UpperCamelCase__ , default=5_0 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=UpperCamelCase__ , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=UpperCamelCase__ , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5e-4 , type=UpperCamelCase__ , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1e-6 , type=UpperCamelCase__ , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=UpperCamelCase__ , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=UpperCamelCase__ , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=UpperCamelCase__ , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=UpperCamelCase__ , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=UpperCamelCase__ , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=UpperCamelCase__ , default=5_6 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=UpperCamelCase__ , default=5_0_0 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=UpperCamelCase__ , default=4_0_0_0 , help="""Checkpoint interval.""" ) UpperCAmelCase__ : Dict = parser.parse_args() sanity_checks(UpperCamelCase__ ) # ARGS # init_gpu_params(UpperCamelCase__ ) set_seed(UpperCamelCase__ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite''' """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f'''Experiment will be dumped and logged in {args.dump_path}''' ) # SAVE PARAMS # logger.info(f'''Param: {args}''' ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(UpperCamelCase__ ) , UpperCamelCase__ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = MODEL_CLASSES[args.student_type] UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase__ : Optional[Any] = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase__ : Any = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase__ : Any = tokenizer.all_special_tokens.index(UpperCamelCase__ ) UpperCAmelCase__ : str = tokenizer.all_special_ids[idx] logger.info(f'''Special tokens {special_tok_ids}''' ) UpperCAmelCase__ : Any = special_tok_ids UpperCAmelCase__ : str = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f'''Loading data from {args.data_file}''' ) with open(args.data_file , """rb""" ) as fp: UpperCAmelCase__ : str = pickle.load(UpperCamelCase__ ) if args.mlm: logger.info(f'''Loading token counts from {args.token_counts} (already pre-computed)''' ) with open(args.token_counts , """rb""" ) as fp: UpperCAmelCase__ : int = pickle.load(UpperCamelCase__ ) UpperCAmelCase__ : Optional[Any] = np.maximum(UpperCamelCase__ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase__ : Tuple = 0.0 # do not predict special tokens UpperCAmelCase__ : Any = torch.from_numpy(UpperCamelCase__ ) else: UpperCAmelCase__ : Tuple = None UpperCAmelCase__ : Optional[int] = LmSeqsDataset(params=UpperCamelCase__ , data=UpperCamelCase__ ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f'''Loading student config from {args.student_config}''' ) UpperCAmelCase__ : int = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase__ : Optional[int] = True if args.student_pretrained_weights is not None: logger.info(f'''Loading pretrained weights from {args.student_pretrained_weights}''' ) UpperCAmelCase__ : str = student_model_class.from_pretrained(args.student_pretrained_weights , config=UpperCamelCase__ ) else: UpperCAmelCase__ : Any = student_model_class(UpperCamelCase__ ) if args.n_gpu > 0: student.to(f'''cuda:{args.local_rank}''' ) logger.info("""Student loaded.""" ) # TEACHER # UpperCAmelCase__ : int = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=UpperCamelCase__ ) if args.n_gpu > 0: teacher.to(f'''cuda:{args.local_rank}''' ) logger.info(f'''Teacher loaded from {args.teacher_name}.''' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(UpperCamelCase__ , UpperCamelCase__ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(UpperCamelCase__ , UpperCamelCase__ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase__ : Optional[Any] = Distiller( params=UpperCamelCase__ , dataset=UpperCamelCase__ , token_probs=UpperCamelCase__ , student=UpperCamelCase__ , teacher=UpperCamelCase__ ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
407
1
'''simple docstring''' import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def _a( UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] =4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int =4 SCREAMING_SNAKE_CASE__ : Any =4_8 SCREAMING_SNAKE_CASE__ : List[Any] ='''pixelshuffle_aux''' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] =[6, 6, 6, 6] SCREAMING_SNAKE_CASE__ : Tuple =6_0 SCREAMING_SNAKE_CASE__ : List[Any] =[6, 6, 6, 6] SCREAMING_SNAKE_CASE__ : Tuple ='''pixelshuffledirect''' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[Any] =4 SCREAMING_SNAKE_CASE__ : Any ='''nearest+conv''' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Union[str, Any] =1 SCREAMING_SNAKE_CASE__ : int =1 SCREAMING_SNAKE_CASE__ : Any =1_2_6 SCREAMING_SNAKE_CASE__ : Dict =7 SCREAMING_SNAKE_CASE__ : Optional[Any] =2_5_5.0 SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''''' return config def _a( UpperCamelCase__ : Tuple, UpperCamelCase__ : Dict ): '''simple docstring''' if "patch_embed.proj" in name and "layers" not in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''patch_embed.proj''', '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''patch_embed.norm''', '''embeddings.patch_embeddings.layernorm''' ) if "layers" in name: SCREAMING_SNAKE_CASE__ : List[str] =name.replace('''layers''', '''encoder.stages''' ) if "residual_group.blocks" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''residual_group.blocks''', '''layers''' ) if "attn.proj" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''attn.proj''', '''attention.output.dense''' ) if "attn" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] =name.replace('''attn''', '''attention.self''' ) if "norm1" in name: SCREAMING_SNAKE_CASE__ : Any =name.replace('''norm1''', '''layernorm_before''' ) if "norm2" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''norm2''', '''layernorm_after''' ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] =name.replace('''mlp.fc1''', '''intermediate.dense''' ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ : Optional[int] =name.replace('''mlp.fc2''', '''output.dense''' ) if "q_bias" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''q_bias''', '''query.bias''' ) if "k_bias" in name: SCREAMING_SNAKE_CASE__ : List[str] =name.replace('''k_bias''', '''key.bias''' ) if "v_bias" in name: SCREAMING_SNAKE_CASE__ : List[str] =name.replace('''v_bias''', '''value.bias''' ) if "cpb_mlp" in name: SCREAMING_SNAKE_CASE__ : int =name.replace('''cpb_mlp''', '''continuous_position_bias_mlp''' ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ : Tuple =name.replace('''patch_embed.proj''', '''patch_embed.projection''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE__ : Optional[Any] ='''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE__ : Optional[int] ='''layernorm.bias''' if "conv_first" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''conv_first''', '''first_convolution''' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: SCREAMING_SNAKE_CASE__ : Any =name.replace('''conv_last''', '''final_convolution''' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''conv_before_upsample.0''', '''conv_before_upsample''' ) if "upsample.0" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''upsample.0''', '''upsample.convolution_0''' ) if "upsample.2" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] =name.replace('''upsample.2''', '''upsample.convolution_1''' ) SCREAMING_SNAKE_CASE__ : Tuple ='''upsample.''' + name elif config.upsampler == "pixelshuffledirect": SCREAMING_SNAKE_CASE__ : int =name.replace('''upsample.0.weight''', '''upsample.conv.weight''' ) SCREAMING_SNAKE_CASE__ : str =name.replace('''upsample.0.bias''', '''upsample.conv.bias''' ) else: pass else: SCREAMING_SNAKE_CASE__ : int ='''swin2sr.''' + name return name def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Tuple ): '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : List[Any] =orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] =key.split('''.''' ) SCREAMING_SNAKE_CASE__ : List[Any] =int(key_split[1] ) SCREAMING_SNAKE_CASE__ : Dict =int(key_split[4] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =config.embed_dim if "weight" in key: SCREAMING_SNAKE_CASE__ : List[Any] =val[:dim, :] SCREAMING_SNAKE_CASE__ : Union[str, Any] =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ : Tuple =val[-dim:, :] else: SCREAMING_SNAKE_CASE__ : str =val[:dim] SCREAMING_SNAKE_CASE__ : List[Any] =val[dim : dim * 2] SCREAMING_SNAKE_CASE__ : Dict =val[-dim:] pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =val return orig_state_dict def _a( UpperCamelCase__ : str, UpperCamelCase__ : Optional[int], UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =get_config(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =SwinaSRForImageSuperResolution(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =torch.hub.load_state_dict_from_url(UpperCamelCase__, map_location='''cpu''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =convert_state_dict(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: raise ValueError('''Missing keys when converting: {}'''.format(UpperCamelCase__ ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(f"Unexpected key {key} in state_dict" ) # verify values SCREAMING_SNAKE_CASE__ : Any ='''https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true''' SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open(requests.get(UpperCamelCase__, stream=UpperCamelCase__ ).raw ).convert('''RGB''' ) SCREAMING_SNAKE_CASE__ : List[Any] =SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE__ : List[Any] =1_2_6 if '''Jpeg''' in checkpoint_url else 2_5_6 SCREAMING_SNAKE_CASE__ : str =Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE__ : int =transforms(UpperCamelCase__ ).unsqueeze(0 ) if config.num_channels == 1: SCREAMING_SNAKE_CASE__ : Optional[Any] =pixel_values[:, 0, :, :].unsqueeze(1 ) SCREAMING_SNAKE_CASE__ : List[str] =model(UpperCamelCase__ ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int =torch.Size([1, 3, 5_1_2, 5_1_2] ) SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor( [[-0.7_0_8_7, -0.7_1_3_8, -0.6_7_2_1], [-0.8_3_4_0, -0.8_0_9_5, -0.7_2_9_8], [-0.9_1_4_9, -0.8_4_1_4, -0.7_9_4_0]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] ) SCREAMING_SNAKE_CASE__ : Dict =torch.tensor( [[-0.7_7_7_5, -0.8_1_0_5, -0.8_9_3_3], [-0.7_7_6_4, -0.8_3_5_6, -0.9_2_2_5], [-0.7_9_7_6, -0.8_6_8_6, -0.9_5_7_9]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here SCREAMING_SNAKE_CASE__ : Tuple =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor( [[-0.8_0_3_5, -0.7_5_0_4, -0.7_4_9_1], [-0.8_5_3_8, -0.8_1_2_4, -0.7_7_8_2], [-0.8_8_0_4, -0.8_6_5_1, -0.8_4_9_3]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] =torch.Size([1, 3, 5_1_2, 5_1_2] ) SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor( [[-0.7_6_6_9, -0.8_6_6_2, -0.8_7_6_7], [-0.8_8_1_0, -0.9_9_6_2, -0.9_8_2_0], [-0.9_3_4_0, -1.0_3_2_2, -1.1_1_4_9]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] ) SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.tensor( [[-0.5_2_3_8, -0.5_5_5_7, -0.6_3_2_1], [-0.6_0_1_6, -0.5_9_0_3, -0.6_3_9_1], [-0.6_2_4_4, -0.6_3_3_4, -0.6_8_8_9]] ) assert ( outputs.reconstruction.shape == expected_shape ), f"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3], UpperCamelCase__, atol=1e-3 ) print('''Looks ok!''' ) SCREAMING_SNAKE_CASE__ : List[str] ={ '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''': ( '''swin2SR-classical-sr-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth''': ( '''swin2SR-classical-sr-x4-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth''': ( '''swin2SR-compressed-sr-x4-48''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth''': ( '''swin2SR-lightweight-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth''': ( '''swin2SR-realworld-sr-x4-64-bsrgan-psnr''' ), } SCREAMING_SNAKE_CASE__ : int =url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(UpperCamelCase__ ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub(f"caidas/{model_name}" ) processor.push_to_hub(f"caidas/{model_name}" ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth', type=str, help='URL of the original Swin2SR checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the converted model to the hub.') a_ = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
665
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters a_ = False a_ = False def _a( UpperCamelCase__ : Namespace ): '''simple docstring''' return TrainCommand(UpperCamelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =parser.add_parser('''train''' , help='''CLI tool to train a model on a task.''' ) train_parser.add_argument( '''--train_data''' , type=__lowercase , required=__lowercase , help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.''' , ) train_parser.add_argument( '''--column_label''' , type=__lowercase , default=0 , help='''Column of the dataset csv file with example labels.''' ) train_parser.add_argument( '''--column_text''' , type=__lowercase , default=1 , help='''Column of the dataset csv file with example texts.''' ) train_parser.add_argument( '''--column_id''' , type=__lowercase , default=2 , help='''Column of the dataset csv file with example ids.''' ) train_parser.add_argument( '''--skip_first_row''' , action='''store_true''' , help='''Skip the first row of the csv file (headers).''' ) train_parser.add_argument('''--validation_data''' , type=__lowercase , default='''''' , help='''path to validation dataset.''' ) train_parser.add_argument( '''--validation_split''' , type=__lowercase , default=0.1 , help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.''' , ) train_parser.add_argument('''--output''' , type=__lowercase , default='''./''' , help='''path to saved the trained model.''' ) train_parser.add_argument( '''--task''' , type=__lowercase , default='''text_classification''' , help='''Task to train the model on.''' ) train_parser.add_argument( '''--model''' , type=__lowercase , default='''bert-base-uncased''' , help='''Model\'s name or path to stored model.''' ) train_parser.add_argument('''--train_batch_size''' , type=__lowercase , default=32 , help='''Batch size for training.''' ) train_parser.add_argument('''--valid_batch_size''' , type=__lowercase , default=64 , help='''Batch size for validation.''' ) train_parser.add_argument('''--learning_rate''' , type=__lowercase , default=3e-5 , help='''Learning rate.''' ) train_parser.add_argument('''--adam_epsilon''' , type=__lowercase , default=1e-08 , help='''Epsilon for Adam optimizer.''' ) train_parser.set_defaults(func=__lowercase ) def __init__( self : Tuple , __lowercase : Namespace ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =logging.get_logger('''transformers-cli/training''' ) SCREAMING_SNAKE_CASE__ : int ='''tf''' if is_tf_available() else '''torch''' os.makedirs(args.output , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =args.output SCREAMING_SNAKE_CASE__ : str =args.column_label SCREAMING_SNAKE_CASE__ : List[Any] =args.column_text SCREAMING_SNAKE_CASE__ : Tuple =args.column_id self.logger.info(F"Loading {args.task} pipeline for {args.model}" ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : List[str] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"Loading dataset from {args.train_data}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =None if args.validation_data: self.logger.info(F"Loading validation dataset from {args.validation_data}" ) SCREAMING_SNAKE_CASE__ : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =args.validation_split SCREAMING_SNAKE_CASE__ : List[Any] =args.train_batch_size SCREAMING_SNAKE_CASE__ : Any =args.valid_batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =args.learning_rate SCREAMING_SNAKE_CASE__ : int =args.adam_epsilon def __magic_name__ ( self : Any ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __magic_name__ ( self : Optional[int] ) -> Tuple: raise NotImplementedError def __magic_name__ ( self : Dict ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
665
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
class __A : def __init__( self : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : int ): lowerCAmelCase : Optional[Any] = name lowerCAmelCase : int = val def __str__( self : str ): return f"{self.__class__.__name__}({self.name}, {self.val})" def __lt__( self : Union[str, Any] , UpperCAmelCase_ : Dict ): return self.val < other.val class __A : def __init__( self : Union[str, Any] , UpperCAmelCase_ : str ): lowerCAmelCase : Optional[Any] = {} lowerCAmelCase : Tuple = {} lowerCAmelCase : Optional[Any] = self.build_heap(UpperCAmelCase_ ) def __getitem__( self : Union[str, Any] , UpperCAmelCase_ : str ): return self.get_value(UpperCAmelCase_ ) def lowercase__ ( self : int , UpperCAmelCase_ : Any ): return (idx - 1) // 2 def lowercase__ ( self : int , UpperCAmelCase_ : str ): return idx * 2 + 1 def lowercase__ ( self : Optional[int] , UpperCAmelCase_ : Any ): return idx * 2 + 2 def lowercase__ ( self : List[str] , UpperCAmelCase_ : List[Any] ): return self.heap_dict[key] def lowercase__ ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): lowerCAmelCase : Optional[Any] = len(UpperCAmelCase_ ) - 1 lowerCAmelCase : Union[str, Any] = self.get_parent_idx(UpperCAmelCase_ ) for idx, i in enumerate(UpperCAmelCase_ ): lowerCAmelCase : Any = idx lowerCAmelCase : Union[str, Any] = i.val for i in range(UpperCAmelCase_ , -1 , -1 ): self.sift_down(UpperCAmelCase_ , UpperCAmelCase_ ) return array def lowercase__ ( self : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any ): while True: lowerCAmelCase : Optional[int] = self.get_left_child_idx(UpperCAmelCase_ ) # noqa: E741 lowerCAmelCase : Union[str, Any] = self.get_right_child_idx(UpperCAmelCase_ ) lowerCAmelCase : Any = idx if l < len(UpperCAmelCase_ ) and array[l] < array[idx]: lowerCAmelCase : Tuple = l if r < len(UpperCAmelCase_ ) and array[r] < array[smallest]: lowerCAmelCase : Any = r if smallest != idx: lowerCAmelCase , lowerCAmelCase : Union[str, Any] = array[smallest], array[idx] ( ( lowerCAmelCase ) , ( lowerCAmelCase ) , ) : List[Any] = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) lowerCAmelCase : List[str] = smallest else: break def lowercase__ ( self : Any , UpperCAmelCase_ : Optional[Any] ): lowerCAmelCase : Optional[Any] = self.get_parent_idx(UpperCAmelCase_ ) while p >= 0 and self.heap[p] > self.heap[idx]: lowerCAmelCase , lowerCAmelCase : Optional[int] = self.heap[idx], self.heap[p] lowerCAmelCase , lowerCAmelCase : Union[str, Any] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) lowerCAmelCase : Dict = p lowerCAmelCase : Optional[Any] = self.get_parent_idx(UpperCAmelCase_ ) def lowercase__ ( self : str ): return self.heap[0] def lowercase__ ( self : int ): lowerCAmelCase , lowerCAmelCase : str = self.heap[-1], self.heap[0] lowerCAmelCase , lowerCAmelCase : Dict = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) lowerCAmelCase : Any = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def lowercase__ ( self : Any , UpperCAmelCase_ : Any ): self.heap.append(UpperCAmelCase_ ) lowerCAmelCase : str = len(self.heap ) - 1 lowerCAmelCase : List[Any] = node.val self.sift_up(len(self.heap ) - 1 ) def lowercase__ ( self : Optional[int] ): return len(self.heap ) == 0 def lowercase__ ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int ): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" lowerCAmelCase : Optional[int] = new_value lowerCAmelCase : str = new_value self.sift_up(self.idx_of_element[node] ) __A : Tuple = Node('''R''', -1) __A : int = Node('''B''', 6) __A : int = Node('''A''', 3) __A : Optional[Any] = Node('''X''', 1) __A : List[str] = Node('''E''', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __A : Optional[int] = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('''Min Heap - before decrease key''') for i in my_min_heap.heap: print(i) print('''Min Heap - After decrease key of node [B -> -17]''') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
343
0
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 100 ) -> int: _a = 0 _a = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
521
'''simple docstring''' from collections import defaultdict from math import ceil, sqrt def _lowerCamelCase ( lowercase : int = 100_0000 , lowercase : int = 10 ) -> int: _a = defaultdict(lowercase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: _a = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: _a = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f"""{solution() = }""")
521
1
"""simple docstring""" from math import isqrt, loga def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = False return [i for i in range(2 , UpperCamelCase_ ) if is_prime[i]] def _lowerCAmelCase ( UpperCamelCase_ = 80_0800 , UpperCamelCase_ = 80_0800 ): __SCREAMING_SNAKE_CASE = degree * loga(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = int(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = calculate_prime_numbers(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = len(UpperCamelCase_ ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(F"""{solution() = }""")
155
"""simple docstring""" def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): if number < 0 or shift_amount < 0: raise ValueError("""both inputs must be positive integers""" ) __SCREAMING_SNAKE_CASE = str(bin(UpperCamelCase_ ) ) binary_number += "0" * shift_amount return binary_number def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): if number < 0 or shift_amount < 0: raise ValueError("""both inputs must be positive integers""" ) __SCREAMING_SNAKE_CASE = str(bin(UpperCamelCase_ ) )[2:] if shift_amount >= len(UpperCamelCase_ ): return "0b0" __SCREAMING_SNAKE_CASE = binary_number[: len(UpperCamelCase_ ) - shift_amount] return "0b" + shifted_binary_number def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): if number >= 0: # Get binary representation of positive number __SCREAMING_SNAKE_CASE = """0""" + str(bin(UpperCamelCase_ ) ).strip("""-""" )[2:] else: # Get binary (2's complement) representation of negative number __SCREAMING_SNAKE_CASE = len(bin(UpperCamelCase_ )[3:] ) # Find 2's complement of number __SCREAMING_SNAKE_CASE = bin(abs(UpperCamelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( """1""" + """0""" * (binary_number_length - len(UpperCamelCase_ )) + binary_number ) if shift_amount >= len(UpperCamelCase_ ): return "0b" + binary_number[0] * len(UpperCamelCase_ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(UpperCamelCase_ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
155
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = KandinskyVaaImgaImgPipeline snake_case_ = ["""image_embeds""", """negative_image_embeds""", """image"""] snake_case_ = [ """image_embeds""", """negative_image_embeds""", """image""", ] snake_case_ = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[str] ) -> Tuple: return 32 @property def __magic_name__ ( self : List[str] ) -> str: return 32 @property def __magic_name__ ( self : Any ) -> Optional[int]: return self.time_input_dim @property def __magic_name__ ( self : List[Any] ) -> int: return self.time_input_dim * 4 @property def __magic_name__ ( self : Tuple ) -> Optional[int]: return 1_00 @property def __magic_name__ ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : Optional[int] =UNetaDConditionModel(**__lowercase ) return model @property def __magic_name__ ( self : Dict ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __magic_name__ ( self : Tuple ) -> Optional[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =VQModel(**self.dummy_movq_kwargs ) return model def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =self.dummy_unet SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''num_train_timesteps''': 10_00, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } SCREAMING_SNAKE_CASE__ : str =DDIMScheduler(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __magic_name__ ( self : str , __lowercase : Optional[Any] , __lowercase : Any=0 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowercase ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[Any] =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any =Image.fromarray(np.uinta(__lowercase ) ).convert('''RGB''' ).resize((2_56, 2_56) ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : Dict =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : str ={ '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] ='''cpu''' SCREAMING_SNAKE_CASE__ : Tuple =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Tuple =np.array( [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : str =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ : List[Any] ='''A red cartoon frog, 4k''' SCREAMING_SNAKE_CASE__ : Optional[int] =KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ : int =output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
710
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = JukeboxTokenizer snake_case_ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __magic_name__ ( self : Optional[int] ) -> str: import torch SCREAMING_SNAKE_CASE__ : List[str] =JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) SCREAMING_SNAKE_CASE__ : str =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : str =[ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __magic_name__ ( self : Any ) -> List[str]: import torch SCREAMING_SNAKE_CASE__ : int =JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] =[ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
665
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class lowercase ( unittest.TestCase ): def lowercase_ ( self ): """simple docstring""" lowerCAmelCase__ : List[str] = inspect.getfile(accelerate.test_utils ) lowerCAmelCase__ : Any = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) lowerCAmelCase__ : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) lowerCAmelCase__ : Optional[int] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def lowercase_ ( self ): """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) lowerCAmelCase__ : List[Any] = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def lowercase_ ( self ): """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) lowerCAmelCase__ : Union[str, Any] = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def lowercase_ ( self ): """simple docstring""" lowerCAmelCase__ : Tuple = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def lowercase_ ( self ): """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) lowerCAmelCase__ : Optional[Any] = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) if __name__ == "__main__": A__ : Union[str, Any] = Accelerator() A__ : List[Any] = (accelerator.state.process_index + 2, 1_0) A__ : Tuple = torch.randint(0, 1_0, shape).to(accelerator.device) A__ : List[Any] = "" A__ : Any = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." A__ : Any = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." A__ : Optional[Any] = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
233
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> Tuple: '''simple docstring''' if not head: return True # split the list to two parts snake_case__ , snake_case__ : Dict = head.next, head while fast and fast.next: snake_case__ : Any = fast.next.next snake_case__ : int = slow.next snake_case__ : Dict = slow.next snake_case__ : List[str] = None # Don't forget here! But forget still works! # reverse the second part snake_case__ : Tuple = None while second: snake_case__ : Tuple = second.next snake_case__ : Any = node snake_case__ : str = second snake_case__ : Optional[Any] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False snake_case__ : List[Any] = node.next snake_case__ : int = head.next return True def UpperCamelCase__ ( __magic_name__ : Any ) -> Optional[Any]: '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) snake_case__ : List[Any] = head while fast and fast.next: snake_case__ , snake_case__ : Any = fast.next.next, slow.next # 2. Push the second half into the stack snake_case__ : Tuple = [slow.val] while slow.next: snake_case__ : Optional[Any] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False snake_case__ : str = cur.next return True def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Tuple: '''simple docstring''' if not head or not head.next: return True snake_case__ : int = {} snake_case__ : Union[str, Any] = 0 while head: if head.val in d: d[head.val].append(__magic_name__ ) else: snake_case__ : Tuple = [pos] snake_case__ : Optional[Any] = head.next pos += 1 snake_case__ : int = pos - 1 snake_case__ : str = 0 for v in d.values(): if len(__magic_name__ ) % 2 != 0: middle += 1 else: snake_case__ : List[str] = 0 for i in range(0 , len(__magic_name__ ) ): if v[i] + v[len(__magic_name__ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
38
0
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _UpperCAmelCase ( lowerCAmelCase__ , unittest.TestCase): _lowerCAmelCase : Optional[Any] = CodeGenTokenizer _lowerCAmelCase : List[str] = CodeGenTokenizerFast _lowerCAmelCase : List[str] = True _lowerCAmelCase : List[str] = {"""add_prefix_space""": True} _lowerCAmelCase : Tuple = False def _snake_case ( self : List[Any] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ : Any = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', '''<|endoftext|>''', ] snake_case_ : Union[str, Any] = dict(zip(lowercase_ , range(len(lowercase_ ) ) ) ) snake_case_ : Optional[int] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] snake_case_ : int = {'''unk_token''': '''<unk>'''} snake_case_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case_ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowercase_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowercase_ ) ) def _snake_case ( self : Optional[Any] , **lowercase_ : str ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **lowercase_ ) def _snake_case ( self : int , **lowercase_ : str ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **lowercase_ ) def _snake_case ( self : int , lowercase_ : Any ): snake_case_ : str = '''lower newer''' snake_case_ : str = '''lower newer''' return input_text, output_text def _snake_case ( self : Dict ): snake_case_ : List[str] = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case_ : List[Any] = '''lower newer''' snake_case_ : int = ['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] snake_case_ : Optional[Any] = tokenizer.tokenize(lowercase_ , add_prefix_space=lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) snake_case_ : Optional[int] = tokens + [tokenizer.unk_token] snake_case_ : Tuple = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_ ) , lowercase_ ) def _snake_case ( self : Optional[int] ): if not self.test_rust_tokenizer: return snake_case_ : Dict = self.get_tokenizer() snake_case_ : str = self.get_rust_tokenizer(add_prefix_space=lowercase_ ) snake_case_ : Union[str, Any] = '''lower newer''' # Testing tokenization snake_case_ : Tuple = tokenizer.tokenize(lowercase_ , add_prefix_space=lowercase_ ) snake_case_ : Union[str, Any] = rust_tokenizer.tokenize(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) # Testing conversion to ids without special tokens snake_case_ : Optional[Any] = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ , add_prefix_space=lowercase_ ) snake_case_ : str = rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) # Testing conversion to ids with special tokens snake_case_ : Dict = self.get_rust_tokenizer(add_prefix_space=lowercase_ ) snake_case_ : Union[str, Any] = tokenizer.encode(lowercase_ , add_prefix_space=lowercase_ ) snake_case_ : List[Any] = rust_tokenizer.encode(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) # Testing the unknown token snake_case_ : Dict = tokens + [rust_tokenizer.unk_token] snake_case_ : int = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(lowercase_ ) , lowercase_ ) def _snake_case ( self : Any , *lowercase_ : Any , **lowercase_ : Optional[Any] ): # It's very difficult to mix/test pretokenization with byte-level # And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _snake_case ( self : Tuple , lowercase_ : Dict=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case_ : List[str] = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) # Simple input snake_case_ : Any = '''This is a simple input''' snake_case_ : Tuple = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case_ : Optional[Any] = ('''This is a simple input''', '''This is a pair''') snake_case_ : Optional[Any] = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(lowercase_ , tokenizer_r.encode , lowercase_ , max_length=lowercase_ , padding='''max_length''' ) # Simple input self.assertRaises(lowercase_ , tokenizer_r.encode_plus , lowercase_ , max_length=lowercase_ , padding='''max_length''' ) # Simple input self.assertRaises( lowercase_ , tokenizer_r.batch_encode_plus , lowercase_ , max_length=lowercase_ , padding='''max_length''' , ) # Pair input self.assertRaises(lowercase_ , tokenizer_r.encode , lowercase_ , max_length=lowercase_ , padding='''max_length''' ) # Pair input self.assertRaises(lowercase_ , tokenizer_r.encode_plus , lowercase_ , max_length=lowercase_ , padding='''max_length''' ) # Pair input self.assertRaises( lowercase_ , tokenizer_r.batch_encode_plus , lowercase_ , max_length=lowercase_ , padding='''max_length''' , ) def _snake_case ( self : Union[str, Any] ): snake_case_ : int = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token='''<pad>''' ) # Simple input snake_case_ : str = '''This is a simple input''' snake_case_ : List[Any] = ['''This is a simple input looooooooong''', '''This is a simple input'''] snake_case_ : Dict = ('''This is a simple input''', '''This is a pair''') snake_case_ : Union[str, Any] = [ ('''This is a simple input loooooong''', '''This is a simple input'''), ('''This is a simple pair loooooong''', '''This is a simple pair'''), ] snake_case_ : List[Any] = tokenizer.pad_token_id snake_case_ : List[Any] = tokenizer(lowercase_ , padding='''max_length''' , max_length=30 , return_tensors='''np''' ) snake_case_ : Tuple = tokenizer(lowercase_ , padding=lowercase_ , truncate=lowercase_ , return_tensors='''np''' ) snake_case_ : Union[str, Any] = tokenizer(*lowercase_ , padding='''max_length''' , max_length=60 , return_tensors='''np''' ) snake_case_ : Optional[Any] = tokenizer(lowercase_ , padding=lowercase_ , truncate=lowercase_ , return_tensors='''np''' ) # s # test single string max_length padding self.assertEqual(out_s['''input_ids'''].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['''input_ids'''] ) self.assertTrue(0 in out_s['''attention_mask'''] ) # s2 # test automatic padding self.assertEqual(out_sa['''input_ids'''].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['''input_ids'''][0] ) self.assertFalse(0 in out_sa['''attention_mask'''][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['''input_ids'''][1] ) self.assertTrue(0 in out_sa['''attention_mask'''][1] ) # p # test single pair max_length padding self.assertEqual(out_p['''input_ids'''].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['''input_ids'''] ) self.assertTrue(0 in out_p['''attention_mask'''] ) # p2 # test automatic padding pair self.assertEqual(out_pa['''input_ids'''].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['''input_ids'''][0] ) self.assertFalse(0 in out_pa['''attention_mask'''][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['''input_ids'''][1] ) self.assertTrue(0 in out_pa['''attention_mask'''][1] ) def _snake_case ( self : Dict ): snake_case_ : Any = '''$$$''' snake_case_ : str = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=lowercase_ , add_bos_token=lowercase_ ) snake_case_ : Optional[int] = '''This is a simple input''' snake_case_ : str = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case_ : Any = tokenizer.bos_token_id snake_case_ : List[Any] = tokenizer(lowercase_ ) snake_case_ : Optional[Any] = tokenizer(lowercase_ ) self.assertEqual(out_s.input_ids[0] , lowercase_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) snake_case_ : List[str] = tokenizer.decode(out_s.input_ids ) snake_case_ : Optional[Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , lowercase_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def _snake_case ( self : Optional[Any] ): snake_case_ : List[Any] = CodeGenTokenizer.from_pretrained('''Salesforce/codegen-350M-mono''' ) snake_case_ : List[str] = '''\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#''' snake_case_ : Dict = '''\nif len_a > len_b: result = a\nelse: result = b''' snake_case_ : Tuple = tokenizer.encode(lowercase_ ) snake_case_ : List[str] = ['''^#''', re.escape('''<|endoftext|>''' ), '''^\'\'\'''', '''^"""''', '''\n\n\n'''] snake_case_ : Any = tokenizer.decode(lowercase_ , truncate_before_pattern=lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) def _snake_case ( self : str ): pass
485
"""simple docstring""" import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def __lowercase ( _a ): return np.dot(_a , _a ) class _UpperCAmelCase : def __init__( self : int , *, lowercase_ : float = np.inf , lowercase_ : str = "linear" , lowercase_ : float = 0.0 , ): snake_case_ : Optional[Any] = regularization snake_case_ : Tuple = gamma if kernel == "linear": snake_case_ : int = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('''rbf kernel requires gamma''' ) if not isinstance(self.gamma , (float, int) ): raise ValueError('''gamma must be float or int''' ) if not self.gamma > 0: raise ValueError('''gamma must be > 0''' ) snake_case_ : int = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: snake_case_ : List[Any] = f"Unknown kernel: {kernel}" raise ValueError(lowercase_ ) def _snake_case ( self : int , lowercase_ : ndarray , lowercase_ : ndarray ): return np.dot(lowercase_ , lowercase_ ) def _snake_case ( self : int , lowercase_ : ndarray , lowercase_ : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _snake_case ( self : Any , lowercase_ : list[ndarray] , lowercase_ : ndarray ): snake_case_ : Union[str, Any] = observations snake_case_ : int = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((snake_case_), ) : List[str] = np.shape(lowercase_ ) def to_minimize(lowercase_ : ndarray ) -> float: snake_case_ : Tuple = 0 ((snake_case_), ) : Optional[Any] = np.shape(lowercase_ ) for i in range(lowercase_ ): for j in range(lowercase_ ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(lowercase_ ) snake_case_ : Optional[Any] = LinearConstraint(lowercase_ , 0 , 0 ) snake_case_ : str = Bounds(0 , self.regularization ) snake_case_ : int = minimize( lowercase_ , np.ones(lowercase_ ) , bounds=lowercase_ , constraints=[ly_contraint] ).x snake_case_ : Optional[Any] = l_star # calculating mean offset of separation plane to points snake_case_ : List[Any] = 0 for i in range(lowercase_ ): for j in range(lowercase_ ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) snake_case_ : Union[str, Any] = s / n def _snake_case ( self : List[str] , lowercase_ : ndarray ): snake_case_ : int = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , lowercase_ ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
485
1
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__ ) class __UpperCAmelCase ( snake_case__ ): """simple docstring""" _snake_case : str = field(default='summarization' , metadata={'include_in_asdict_even_if_is_default': True} ) _snake_case : ClassVar[Features] = Features({'text': Value('string' )} ) _snake_case : ClassVar[Features] = Features({'summary': Value('string' )} ) _snake_case : str = "text" _snake_case : str = "summary" @property def A ( self : Any )-> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
505
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer _A = logging.get_logger(__name__) _A = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} # See all MVP models at https://huggingface.co/models?filter=mvp _A = { "vocab_file": { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json", }, "added_tokens.json": { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json", }, "merges_file": { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt", }, "tokenizer_file": { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json", }, } _A = { "RUCAIBox/mvp": 1_024, } class __UpperCAmelCase ( snake_case__ ): """simple docstring""" _snake_case : Dict = VOCAB_FILES_NAMES _snake_case : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _snake_case : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : Tuple = ['input_ids', 'attention_mask'] _snake_case : Any = MvpTokenizer def __init__( self : str , A_ : int=None , A_ : List[Any]=None , A_ : Optional[Any]=None , A_ : int="replace" , A_ : int="<s>" , A_ : Any="</s>" , A_ : List[str]="</s>" , A_ : Optional[int]="<s>" , A_ : Optional[int]="<unk>" , A_ : Optional[int]="<pad>" , A_ : Union[str, Any]="<mask>" , A_ : str=False , A_ : List[str]=True , **A_ : Union[str, Any] , )-> Any: super().__init__( A_ , A_ , tokenizer_file=A_ , errors=A_ , bos_token=A_ , eos_token=A_ , sep_token=A_ , cls_token=A_ , unk_token=A_ , pad_token=A_ , mask_token=A_ , add_prefix_space=A_ , trim_offsets=A_ , **A_ , ) __UpperCamelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , A_ ) != add_prefix_space: __UpperCamelCase = getattr(A_ , pre_tok_state.pop("type" ) ) __UpperCamelCase = add_prefix_space __UpperCamelCase = pre_tok_class(**A_ ) __UpperCamelCase = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` __UpperCamelCase = "post_processor" __UpperCamelCase = getattr(self.backend_tokenizer , A_ , A_ ) if tokenizer_component_instance: __UpperCamelCase = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __UpperCamelCase = tuple(state["sep"] ) if "cls" in state: __UpperCamelCase = tuple(state["cls"] ) __UpperCamelCase = False if state.get("add_prefix_space" , A_ ) != add_prefix_space: __UpperCamelCase = add_prefix_space __UpperCamelCase = True if state.get("trim_offsets" , A_ ) != trim_offsets: __UpperCamelCase = trim_offsets __UpperCamelCase = True if changes_to_apply: __UpperCamelCase = getattr(A_ , state.pop("type" ) ) __UpperCamelCase = component_class(**A_ ) setattr(self.backend_tokenizer , A_ , A_ ) @property def A ( self : List[str] )-> str: if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def A ( self : Any , A_ : List[Any] )-> List[Any]: __UpperCamelCase = AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else value __UpperCamelCase = value def A ( self : str , *A_ : Dict , **A_ : Dict )-> BatchEncoding: __UpperCamelCase = kwargs.get("is_split_into_words" , A_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*A_ , **A_ ) def A ( self : Tuple , *A_ : str , **A_ : List[str] )-> BatchEncoding: __UpperCamelCase = kwargs.get("is_split_into_words" , A_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*A_ , **A_ ) def A ( self : Optional[int] , A_ : str , A_ : Optional[str] = None )-> Tuple[str]: __UpperCamelCase = self._tokenizer.model.save(A_ , name=A_ ) return tuple(A_ ) def A ( self : Any , A_ : Dict , A_ : Dict=None )-> Union[str, Any]: __UpperCamelCase = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def A ( self : Optional[int] , A_ : List[int] , A_ : Optional[List[int]] = None )-> List[int]: __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 + sep + token_ids_a + sep ) * [0]
505
1
def lowerCamelCase__ ( _lowerCamelCase = 1000 ) ->int: return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
592
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
592
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __lowerCAmelCase : Dict = { "configuration_layoutlmv3": [ "LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv3Config", "LayoutLMv3OnnxConfig", ], "processing_layoutlmv3": ["LayoutLMv3Processor"], "tokenization_layoutlmv3": ["LayoutLMv3Tokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Tuple = ["LayoutLMv3TokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Tuple = [ "LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv3ForQuestionAnswering", "LayoutLMv3ForSequenceClassification", "LayoutLMv3ForTokenClassification", "LayoutLMv3Model", "LayoutLMv3PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[Any] = [ "TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLayoutLMv3ForQuestionAnswering", "TFLayoutLMv3ForSequenceClassification", "TFLayoutLMv3ForTokenClassification", "TFLayoutLMv3Model", "TFLayoutLMv3PreTrainedModel", ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Any = ["LayoutLMv3FeatureExtractor"] __lowerCAmelCase : Tuple = ["LayoutLMv3ImageProcessor"] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys __lowerCAmelCase : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
509
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCAmelCase : Any = logging.get_logger(__name__) __lowerCAmelCase : Optional[Any] = { "vocab_file": "vocab.json", "tokenizer_config_file": "tokenizer_config.json", "merges_file": "merges.txt", } __lowerCAmelCase : List[str] = { "vocab_file": { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json" ), }, "tokenizer_config_file": { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json" ), }, "merges_file": { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt" ), }, } __lowerCAmelCase : Union[str, Any] = "</w>" __lowerCAmelCase : str = "@@ " def UpperCAmelCase_ ( __lowerCAmelCase ) -> Tuple: __lowercase : List[str] = set() __lowercase : Tuple = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowercase : Tuple = char return pairs # Speech2Text2 has no max input length __lowerCAmelCase : Optional[Any] = {"facebook/s2t-wav2vec2-large-en-de": 1_024} class __lowerCAmelCase ( lowerCAmelCase_ ): """simple docstring""" A__ : Union[str, Any] = VOCAB_FILES_NAMES A__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP A__ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : List[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , _snake_case : Optional[Any] , _snake_case : Optional[Any]="<s>" , _snake_case : Tuple="<pad>" , _snake_case : int="</s>" , _snake_case : Optional[Any]="<unk>" , _snake_case : Optional[Any]=False , _snake_case : List[Any]=None , **_snake_case : List[str] , ): super().__init__( unk_token=_snake_case , bos_token=_snake_case , eos_token=_snake_case , pad_token=_snake_case , do_lower_case=_snake_case , **_snake_case , ) __lowercase : Optional[int] = do_lower_case with open(_snake_case , encoding='''utf-8''' ) as vocab_handle: __lowercase : Optional[Any] = json.load(_snake_case ) __lowercase : List[str] = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F'No merges files provided. {self.__class__.__name__} can only be used for decoding.' ) __lowercase : List[str] = None __lowercase : Union[str, Any] = None else: with open(_snake_case , encoding='''utf-8''' ) as merges_handle: __lowercase : Optional[int] = merges_handle.read().split('''\n''' )[:-1] __lowercase : Any = [tuple(merge.split()[:2] ) for merge in merges] __lowercase : Optional[int] = dict(zip(_snake_case , range(len(_snake_case ) ) ) ) __lowercase : List[Any] = {} @property def snake_case_ ( self : str ): return len(self.decoder ) def snake_case_ ( self : Tuple ): return dict(self.encoder , **self.added_tokens_encoder ) def snake_case_ ( self : int , _snake_case : int ): __lowercase : Optional[Any] = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] __lowercase : Any = get_pairs(_snake_case ) if not pairs: return token while True: __lowercase : str = min(_snake_case , key=lambda _snake_case : self.bpe_ranks.get(_snake_case , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __lowercase , __lowercase : List[Any] = bigram __lowercase : Optional[int] = [] __lowercase : List[str] = 0 while i < len(_snake_case ): try: __lowercase : int = word.index(_snake_case , _snake_case ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowercase : Union[str, Any] = j if word[i] == first and i < len(_snake_case ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowercase : Union[str, Any] = tuple(_snake_case ) __lowercase : Dict = new_word if len(_snake_case ) == 1: break else: __lowercase : List[Any] = get_pairs(_snake_case ) __lowercase : List[Any] = ''' '''.join(_snake_case ) if word == "\n " + BPE_TOKEN_MERGES: __lowercase : Optional[int] = '''\n''' + BPE_TOKEN_MERGES if word.endswith(_snake_case ): __lowercase : str = word.replace(_snake_case , '''''' ) __lowercase : List[str] = word.replace(''' ''' , _snake_case ) __lowercase : Union[str, Any] = word return word def snake_case_ ( self : List[str] , _snake_case : List[str] ): if self.bpe_ranks is None: raise ValueError( '''This tokenizer was instantiated without a `merges.txt` file, so''' ''' that it can only be used for decoding, not for encoding.''' '''Make sure to provide `merges.txt` file at instantiation to enable ''' '''encoding.''' ) if self.do_lower_case: __lowercase : Dict = text.lower() __lowercase : str = text.split() __lowercase : Optional[int] = [] for token in text: if token: split_tokens.extend(list(self.bpe(_snake_case ).split(''' ''' ) ) ) return split_tokens def snake_case_ ( self : int , _snake_case : str ): return self.encoder.get(_snake_case , self.encoder.get(self.unk_token ) ) def snake_case_ ( self : Optional[Any] , _snake_case : int ): __lowercase : Dict = self.decoder.get(_snake_case , self.unk_token ) return result def snake_case_ ( self : Union[str, Any] , _snake_case : List[str] ): __lowercase : Tuple = ''' '''.join(_snake_case ) # make sure @@ tokens are concatenated __lowercase : str = ''''''.join(string.split(_snake_case ) ) return string def snake_case_ ( self : Tuple , _snake_case : str , _snake_case : Optional[str] = None ): if not os.path.isdir(_snake_case ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return __lowercase : int = os.path.join( _snake_case , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __lowercase : Optional[Any] = os.path.join( _snake_case , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_snake_case , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_snake_case , ensure_ascii=_snake_case ) + '''\n''' ) __lowercase : Any = 0 if self.bpe_ranks is None: return (vocab_file,) with open(_snake_case , '''w''' , encoding='''utf-8''' ) as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _snake_case : kv[1] ): if index != token_index: logger.warning( F'Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.' ''' Please check that the tokenizer is not corrupted!''' ) __lowercase : Optional[int] = token_index writer.write(''' '''.join(_snake_case ) + '''\n''' ) index += 1 return (vocab_file, merges_file)
509
1
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class _UpperCAmelCase ( snake_case ): @staticmethod @abstractmethod def lowerCAmelCase__ ( a : ArgumentParser ): '''simple docstring''' raise NotImplementedError() @abstractmethod def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' raise NotImplementedError()
706
'''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 UpperCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCamelCase__ = '\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 __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=8 ): """simple docstring""" lowercase_ : int = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 lowercase_ : str = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class _UpperCAmelCase ( snake_case ): def __init__( self : int , a : MultilingualCLIP , a : XLMRobertaTokenizer , a : UNetaDConditionModel , a : Union[DDIMScheduler, DDPMScheduler] , a : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( text_encoder=a , tokenizer=a , unet=a , scheduler=a , movq=a , ) lowercase_ : Dict = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase__ ( self : List[Any] , a : Tuple , a : List[str] , a : Optional[Any] , a : str , a : Tuple , a : List[str] ): '''simple docstring''' if latents is None: lowercase_ : List[str] = randn_tensor(a , generator=a , device=a , dtype=a ) else: if latents.shape != shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) lowercase_ : Optional[int] = latents.to(a ) lowercase_ : str = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase__ ( self : Optional[Any] , a : List[str] , a : List[Any] , a : Union[str, Any] , a : str , a : Tuple=None , ): '''simple docstring''' lowercase_ : Tuple = len(a ) if isinstance(a , a ) else 1 # get prompt text embeddings lowercase_ : Any = self.tokenizer( a , padding="max_length" , truncation=a , max_length=7_7 , return_attention_mask=a , add_special_tokens=a , return_tensors="pt" , ) lowercase_ : Union[str, Any] = text_inputs.input_ids lowercase_ : Tuple = self.tokenizer(a , padding="longest" , return_tensors="pt" ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(a , a ): lowercase_ : Optional[int] = 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}""" ) lowercase_ : List[str] = text_input_ids.to(a ) lowercase_ : int = text_inputs.attention_mask.to(a ) lowercase_ , lowercase_ : Optional[int] = self.text_encoder( input_ids=a , attention_mask=a ) lowercase_ : str = prompt_embeds.repeat_interleave(a , dim=0 ) lowercase_ : int = text_encoder_hidden_states.repeat_interleave(a , dim=0 ) lowercase_ : int = text_mask.repeat_interleave(a , dim=0 ) if do_classifier_free_guidance: lowercase_ : List[str] if negative_prompt is None: lowercase_ : int = [""] * batch_size elif type(a ) is not type(a ): raise TypeError( f"""`negative_prompt` should be the same type to `prompt`, but got {type(a )} !=""" f""" {type(a )}.""" ) elif isinstance(a , a ): lowercase_ : Tuple = [negative_prompt] elif batch_size != len(a ): raise ValueError( f"""`negative_prompt`: {negative_prompt} has batch size {len(a )}, but `prompt`:""" f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" " the batch size of `prompt`." ) else: lowercase_ : Dict = negative_prompt lowercase_ : str = self.tokenizer( a , padding="max_length" , max_length=7_7 , truncation=a , return_attention_mask=a , add_special_tokens=a , return_tensors="pt" , ) lowercase_ : List[Any] = uncond_input.input_ids.to(a ) lowercase_ : Optional[int] = uncond_input.attention_mask.to(a ) lowercase_ , lowercase_ : int = self.text_encoder( input_ids=a , attention_mask=a ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowercase_ : List[str] = negative_prompt_embeds.shape[1] lowercase_ : Dict = negative_prompt_embeds.repeat(1 , a ) lowercase_ : Optional[Any] = negative_prompt_embeds.view(batch_size * num_images_per_prompt , a ) lowercase_ : Any = uncond_text_encoder_hidden_states.shape[1] lowercase_ : List[Any] = uncond_text_encoder_hidden_states.repeat(1 , a , 1 ) lowercase_ : Tuple = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , a , -1 ) lowercase_ : List[Any] = uncond_text_mask.repeat_interleave(a , 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 lowercase_ : Optional[int] = torch.cat([negative_prompt_embeds, prompt_embeds] ) lowercase_ : Tuple = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) lowercase_ : Any = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def lowerCAmelCase__ ( self : Tuple , a : Optional[Any]=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) lowercase_ : List[str] = torch.device(f"""cuda:{gpu_id}""" ) lowercase_ : str = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(a , a ) def lowerCAmelCase__ ( self : Union[str, Any] , a : List[str]=0 ): '''simple docstring''' 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." ) lowercase_ : List[str] = torch.device(f"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=a ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) lowercase_ : List[str] = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: lowercase_ , lowercase_ : Optional[int] = cpu_offload_with_hook(a , a , prev_module_hook=a ) if self.safety_checker is not None: lowercase_ , lowercase_ : Optional[int] = cpu_offload_with_hook(self.safety_checker , a , prev_module_hook=a ) # We'll offload the last model manually. lowercase_ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase__ ( self : Tuple ): '''simple docstring''' if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(a , "_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(a ) def __call__( self : Tuple , a : Union[str, List[str]] , a : Union[torch.FloatTensor, List[torch.FloatTensor]] , a : Union[torch.FloatTensor, List[torch.FloatTensor]] , a : Optional[Union[str, List[str]]] = None , a : int = 5_1_2 , a : int = 5_1_2 , a : int = 1_0_0 , a : float = 4.0 , a : int = 1 , a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a : Optional[torch.FloatTensor] = None , a : Optional[str] = "pil" , a : bool = True , ): '''simple docstring''' if isinstance(a , a ): lowercase_ : List[str] = 1 elif isinstance(a , a ): lowercase_ : int = len(a ) else: raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(a )}""" ) lowercase_ : Tuple = self._execution_device lowercase_ : Dict = batch_size * num_images_per_prompt lowercase_ : Dict = guidance_scale > 1.0 lowercase_ , lowercase_ , lowercase_ : List[str] = self._encode_prompt( a , a , a , a , a ) if isinstance(a , a ): lowercase_ : Optional[int] = torch.cat(a , dim=0 ) if isinstance(a , a ): lowercase_ : int = torch.cat(a , dim=0 ) if do_classifier_free_guidance: lowercase_ : Optional[int] = image_embeds.repeat_interleave(a , dim=0 ) lowercase_ : int = negative_image_embeds.repeat_interleave(a , dim=0 ) lowercase_ : str = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=a ) self.scheduler.set_timesteps(a , device=a ) lowercase_ : List[str] = self.scheduler.timesteps lowercase_ : str = self.unet.config.in_channels lowercase_ , lowercase_ : int = get_new_h_w(a , a , self.movq_scale_factor ) # create initial latent lowercase_ : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , a , a , a , self.scheduler , ) for i, t in enumerate(self.progress_bar(a ) ): # expand the latents if we are doing classifier free guidance lowercase_ : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowercase_ : Optional[int] = {"text_embeds": prompt_embeds, "image_embeds": image_embeds} lowercase_ : Optional[int] = self.unet( sample=a , timestep=a , encoder_hidden_states=a , added_cond_kwargs=a , return_dict=a , )[0] if do_classifier_free_guidance: lowercase_ , lowercase_ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) lowercase_ , lowercase_ : Optional[Any] = noise_pred.chunk(2 ) lowercase_ , lowercase_ : Any = variance_pred.chunk(2 ) lowercase_ : Dict = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) lowercase_ : int = 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"] ): lowercase_ , lowercase_ : str = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 lowercase_ : Tuple = self.scheduler.step( a , a , a , generator=a , ).prev_sample # post-processing lowercase_ : Union[str, Any] = self.movq.decode(a , force_not_quantize=a )["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"]: lowercase_ : List[Any] = image * 0.5 + 0.5 lowercase_ : Optional[int] = image.clamp(0 , 1 ) lowercase_ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowercase_ : List[str] = self.numpy_to_pil(a ) if not return_dict: return (image,) return ImagePipelineOutput(images=a )
640
0
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin snake_case = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class lowerCAmelCase ( UpperCamelCase_ , unittest.TestCase ): A_ : Tuple = SpeechTaTokenizer A_ : List[Any] = False A_ : Optional[Any] = True def _A ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ : Any = SpeechTaTokenizer(a__ ) lowerCAmelCase__ : Optional[int] = AddedToken("<mask>" , lstrip=a__ , rstrip=a__ ) lowerCAmelCase__ : Tuple = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) tokenizer.save_pretrained(self.tmpdirname ) def _A ( self : Dict , a__ : str ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = "this is a test" lowerCAmelCase__ : Optional[Any] = "this is a test" return input_text, output_text def _A ( self : Union[str, Any] , a__ : Any , a__ : Union[str, Any]=False , a__ : str=20 , a__ : Optional[Any]=5 ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ : Tuple = self.get_input_output_texts(a__ ) lowerCAmelCase__ : List[str] = tokenizer.encode(a__ , add_special_tokens=a__ ) lowerCAmelCase__ : Union[str, Any] = tokenizer.decode(a__ , clean_up_tokenization_spaces=a__ ) return text, ids def _A ( self : List[str] ): '''simple docstring''' lowerCAmelCase__ : Any = "<pad>" lowerCAmelCase__ : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def _A ( self : str ): '''simple docstring''' lowerCAmelCase__ : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-4] , "œ" ) self.assertEqual(vocab_keys[-2] , "<mask>" ) self.assertEqual(vocab_keys[-1] , "<ctc_blank>" ) self.assertEqual(len(a__ ) , 81 ) def _A ( self : List[Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def _A ( self : List[str] ): '''simple docstring''' lowerCAmelCase__ : str = self.get_tokenizers(do_lower_case=a__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): lowerCAmelCase__ : List[Any] = tokenizer.vocab_size lowerCAmelCase__ : Any = len(a__ ) self.assertNotEqual(a__ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) lowerCAmelCase__ : int = ["aaaaa bbbbbb", "cccccccccdddddddd"] lowerCAmelCase__ : Tuple = tokenizer.add_tokens(a__ ) lowerCAmelCase__ : Tuple = tokenizer.vocab_size lowerCAmelCase__ : str = len(a__ ) self.assertNotEqual(a__ , 0 ) self.assertEqual(a__ , a__ ) self.assertEqual(a__ , len(a__ ) ) self.assertEqual(a__ , all_size + len(a__ ) ) lowerCAmelCase__ : Optional[Any] = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=a__ ) self.assertGreaterEqual(len(a__ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) lowerCAmelCase__ : Optional[Any] = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} lowerCAmelCase__ : List[Any] = tokenizer.add_special_tokens(a__ ) lowerCAmelCase__ : List[str] = tokenizer.vocab_size lowerCAmelCase__ : Optional[int] = len(a__ ) self.assertNotEqual(a__ , 0 ) self.assertEqual(a__ , a__ ) self.assertEqual(a__ , len(a__ ) ) self.assertEqual(a__ , all_size_a + len(a__ ) ) lowerCAmelCase__ : Dict = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=a__ ) self.assertGreaterEqual(len(a__ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def _A ( self : Any ): '''simple docstring''' pass def _A ( self : List[str] ): '''simple docstring''' pass def _A ( self : Optional[Any] ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = self.get_tokenizer() lowerCAmelCase__ : int = tokenizer.tokenize("This is a test" ) # fmt: off self.assertListEqual(a__ , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) lowerCAmelCase__ : Optional[int] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( a__ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) lowerCAmelCase__ : Optional[Any] = tokenizer.convert_tokens_to_ids(a__ ) # fmt: off self.assertListEqual(a__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on lowerCAmelCase__ : List[str] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) @slow def _A ( self : Optional[int] ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = [ "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " "conditioning on both left and right context in all layers.", "The quick brown fox jumps over the lazy dog.", ] # fmt: off lowerCAmelCase__ : Tuple = { "input_ids": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=a__ , )
378
'''simple docstring''' from math import factorial snake_case = {str(digit): factorial(digit) for digit in range(10)} def UpperCAmelCase_ ( lowerCamelCase_ ): """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError("Parameter number must be int" ) if number < 0: raise ValueError("Parameter number must be greater than or equal to 0" ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(lowerCamelCase_ ) ) def UpperCAmelCase_ ( lowerCamelCase_ = 6_0 , lowerCamelCase_ = 1_0_0_0_0_0_0 ): """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError("Parameters chain_length and number_limit must be int" ) if chain_length <= 0 or number_limit <= 0: raise ValueError( "Parameters chain_length and number_limit must be greater than 0" ) # the counter for the chains with the exact desired length lowerCAmelCase__ : str = 0 # the cached sizes of the previous chains lowerCAmelCase__ : dict[int, int] = {} for start_chain_element in range(1 , lowerCamelCase_ ): # The temporary set will contain the elements of the chain lowerCAmelCase__ : Any = set() lowerCAmelCase__ : int = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. lowerCAmelCase__ : Dict = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(lowerCamelCase_ ) chain_set_length += 1 lowerCAmelCase__ : Dict = digit_factorial_sum(lowerCamelCase_ ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] lowerCAmelCase__ : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution()}')
378
1
import heapq def SCREAMING_SNAKE_CASE__ ( lowercase ) -> set[int]: snake_case : list[list] = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase ,[-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices snake_case : List[Any] = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices snake_case : Union[str, Any] = heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: snake_case : Any = elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase : Dict = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f"""Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}""")
684
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def SCREAMING_SNAKE_CASE__ ( lowercase ) -> str: snake_case : int = [] for line in lines: snake_case : Dict = re.sub(R"""#.*""" ,"""""" ,lowercase ) # remove comments if line: filtered_lines.append(lowercase ) snake_case : Optional[int] = """\n""".join(lowercase ) # Make a hash from all this code snake_case : List[str] = full_str.encode("""utf-8""" ) return shaaaa(lowercase ).hexdigest() # get importable module names and hash for caching lowerCamelCase : Any = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions lowerCamelCase : Optional[int] = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) lowerCamelCase : Tuple = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name lowerCamelCase : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
684
1
"""simple docstring""" from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def a__ ( lowerCAmelCase__ ): return getitem, k def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): return setitem, k, v def a__ ( lowerCAmelCase__ ): return delitem, k def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ ): try: return fun(lowerCAmelCase__ , *lowerCAmelCase__ ), None except Exception as e: return None, e lowerCamelCase = ( _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), ) lowerCamelCase = [ _set("""key_a""", """val_a"""), _set("""key_a""", """val_b"""), ] lowerCamelCase = [ _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), _del("""key_a"""), _del("""key_b"""), _set("""key_a""", """val_a"""), _del("""key_a"""), ] lowerCamelCase = [ _get("""key_a"""), _del("""key_a"""), _set("""key_a""", """val_a"""), _del("""key_a"""), _del("""key_a"""), _get("""key_a"""), ] lowerCamelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCamelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("""key_a""", """val_b"""), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = HashMap(initial_block_size=4 ) UpperCAmelCase_ = {} for _, (fun, *args) in enumerate(lowerCAmelCase__ ): UpperCAmelCase_ , UpperCAmelCase_ = _run_operation(lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = _run_operation(lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ ) assert my_res == py_res assert str(lowerCAmelCase__ ) == str(lowerCAmelCase__ ) assert set(lowerCAmelCase__ ) == set(lowerCAmelCase__ ) assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ) assert set(my.items() ) == set(py.items() ) def a__ ( ): def is_public(lowerCAmelCase__ ) -> bool: return not name.startswith("_" ) UpperCAmelCase_ = {name for name in dir({} ) if is_public(lowerCAmelCase__ )} UpperCAmelCase_ = {name for name in dir(HashMap() ) if is_public(lowerCAmelCase__ )} assert dict_public_names > hash_public_names
82
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING lowerCamelCase = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE ) class lowercase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Union[str, Any] , **_UpperCAmelCase : Optional[int] ) -> str: '''simple docstring''' super().__init__(**_UpperCAmelCase ) if self.framework == "tf": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) requires_backends(self , "vision" ) self.check_model_type(_UpperCAmelCase ) def __call__( self : int , _UpperCAmelCase : Union[str, "Image.Image", List[Dict[str, Any]]] , _UpperCAmelCase : Union[str, List[str]] = None , **_UpperCAmelCase : Optional[int] , ) -> List[Any]: '''simple docstring''' if "text_queries" in kwargs: UpperCAmelCase_ = kwargs.pop("text_queries" ) if isinstance(_UpperCAmelCase , (str, Image.Image) ): UpperCAmelCase_ = {"image": image, "candidate_labels": candidate_labels} else: UpperCAmelCase_ = image UpperCAmelCase_ = super().__call__(_UpperCAmelCase , **_UpperCAmelCase ) return results def lowercase__ ( self : str , **_UpperCAmelCase : List[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {} if "threshold" in kwargs: UpperCAmelCase_ = kwargs["threshold"] if "top_k" in kwargs: UpperCAmelCase_ = kwargs["top_k"] return {}, {}, postprocess_params def lowercase__ ( self : int , _UpperCAmelCase : int ) -> Any: '''simple docstring''' UpperCAmelCase_ = load_image(inputs["image"] ) UpperCAmelCase_ = inputs["candidate_labels"] if isinstance(_UpperCAmelCase , _UpperCAmelCase ): UpperCAmelCase_ = candidate_labels.split("," ) UpperCAmelCase_ = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(_UpperCAmelCase ): UpperCAmelCase_ = self.tokenizer(_UpperCAmelCase , return_tensors=self.framework ) UpperCAmelCase_ = self.image_processor(_UpperCAmelCase , return_tensors=self.framework ) yield { "is_last": i == len(_UpperCAmelCase ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def lowercase__ ( self : int , _UpperCAmelCase : List[Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = model_inputs.pop("target_size" ) UpperCAmelCase_ = model_inputs.pop("candidate_label" ) UpperCAmelCase_ = model_inputs.pop("is_last" ) UpperCAmelCase_ = self.model(**_UpperCAmelCase ) UpperCAmelCase_ = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs} return model_outputs def lowercase__ ( self : str , _UpperCAmelCase : List[str] , _UpperCAmelCase : Any=0.1 , _UpperCAmelCase : List[str]=None ) -> int: '''simple docstring''' UpperCAmelCase_ = [] for model_output in model_outputs: UpperCAmelCase_ = model_output["candidate_label"] UpperCAmelCase_ = BaseModelOutput(_UpperCAmelCase ) UpperCAmelCase_ = self.image_processor.post_process_object_detection( outputs=_UpperCAmelCase , threshold=_UpperCAmelCase , target_sizes=model_output["target_size"] )[0] for index in outputs["scores"].nonzero(): UpperCAmelCase_ = outputs["scores"][index].item() UpperCAmelCase_ = self._get_bounding_box(outputs["boxes"][index][0] ) UpperCAmelCase_ = {"score": score, "label": label, "box": box} results.append(_UpperCAmelCase ) UpperCAmelCase_ = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase : x["score"] , reverse=_UpperCAmelCase ) if top_k: UpperCAmelCase_ = results[:top_k] return results def lowercase__ ( self : str , _UpperCAmelCase : "torch.Tensor" ) -> Dict[str, int]: '''simple docstring''' if self.framework != "pt": raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch." ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = box.int().tolist() UpperCAmelCase_ = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
82
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Any = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys __UpperCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
641
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : Any = { 'tiiuae/falcon-40b': 'https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json', 'tiiuae/falcon-7b': 'https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json', } class lowerCAmelCase__( snake_case__ ): '''simple docstring''' A_ : int = 'falcon' A_ : int = ['past_key_values'] def __init__( self : Optional[Any] , __snake_case : Tuple=65_024 , __snake_case : List[str]=4_544 , __snake_case : Optional[Any]=32 , __snake_case : Any=71 , __snake_case : str=1E-5 , __snake_case : List[str]=0.02 , __snake_case : List[Any]=True , __snake_case : Dict=0.0 , __snake_case : Optional[Any]=0.0 , __snake_case : Any=None , __snake_case : List[Any]=False , __snake_case : Dict=False , __snake_case : Optional[int]=True , __snake_case : List[Any]=True , __snake_case : Optional[Any]=False , __snake_case : Dict=11 , __snake_case : List[str]=11 , **__snake_case : int , ): '''simple docstring''' UpperCAmelCase_ : int = vocab_size # Backward compatibility with n_embed kwarg UpperCAmelCase_ : Union[str, Any] = kwargs.pop('''n_embed''' , __snake_case ) UpperCAmelCase_ : str = hidden_size if n_embed is None else n_embed UpperCAmelCase_ : Tuple = num_hidden_layers UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : Optional[int] = layer_norm_epsilon UpperCAmelCase_ : int = initializer_range UpperCAmelCase_ : Optional[int] = use_cache UpperCAmelCase_ : List[Any] = hidden_dropout UpperCAmelCase_ : Any = attention_dropout UpperCAmelCase_ : Tuple = bos_token_id UpperCAmelCase_ : List[Any] = eos_token_id UpperCAmelCase_ : Any = num_attention_heads if num_kv_heads is None else num_kv_heads UpperCAmelCase_ : Optional[int] = alibi UpperCAmelCase_ : Dict = new_decoder_architecture UpperCAmelCase_ : List[Any] = multi_query # Ignored when new_decoder_architecture is True UpperCAmelCase_ : Tuple = parallel_attn UpperCAmelCase_ : List[Any] = bias super().__init__(bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) @property def _lowerCamelCase ( self : Optional[int] ): '''simple docstring''' return self.hidden_size // self.num_attention_heads @property def _lowerCamelCase ( self : Optional[int] ): '''simple docstring''' return not self.alibi
641
1
'''simple docstring''' def lowerCamelCase__ ( _A ): a : List[str] = [0 for i in range(len(_SCREAMING_SNAKE_CASE ) )] # initialize interval's left pointer and right pointer a : List[str] = 0, 0 for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): # case when current index is inside the interval if i <= right_pointer: a : Tuple = min(right_pointer - i + 1 , z_result[i - left_pointer] ) a : Optional[int] = min_edge while go_next(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: a : Any = i, i + z_result[i] - 1 return z_result def lowerCamelCase__ ( _A , _A , _A ): return i + z_result[i] < len(_SCREAMING_SNAKE_CASE ) and s[z_result[i]] == s[i + z_result[i]] def lowerCamelCase__ ( _A , _A ): a : Tuple = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string a : Tuple = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(_SCREAMING_SNAKE_CASE ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
526
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets lowercase = datasets.logging.get_logger(__name__) lowercase = '''\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = "{COMET}: A Neural Framework for {MT} Evaluation", author = "Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon", booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)", month = nov, year = "2020", address = "Online", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/2020.emnlp-main.213", pages = "2685--2702", } ''' lowercase = '''\ Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM). With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. ''' lowercase = ''' COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric(\'comet\') >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."] >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"] >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results["scores"]]) [0.19, 0.92] ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCamelCase ( datasets.Metric ): '''simple docstring''' def a_ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://unbabel.github.io/COMET/html/index.html" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "sources": datasets.Value("string" , id="sequence" ), "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/Unbabel/COMET"] , reference_urls=[ "https://github.com/Unbabel/COMET", "https://www.aclweb.org/anthology/2020.emnlp-main.213/", "http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6", ] , ) def a_ ( self , a__ ): if self.config_name == "default": __SCREAMING_SNAKE_CASE : Union[str, Any] = comet.load_from_checkpoint(comet.download_model("wmt20-comet-da" ) ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def a_ ( self , a__ , a__ , a__ , a__=None , a__=False ): if gpus is None: __SCREAMING_SNAKE_CASE : List[str] = 1 if torch.cuda.is_available() else 0 __SCREAMING_SNAKE_CASE : Any = {"src": sources, "mt": predictions, "ref": references} __SCREAMING_SNAKE_CASE : int = [dict(zip(a__ , a__ ) ) for t in zip(*data.values() )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.scorer.predict(a__ , gpus=a__ , progress_bar=a__ ) return {"mean_score": mean_score, "scores": scores}
211
0
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed lowerCamelCase : Any = 'true' def lowercase__( A , A=8_2 , A=1_6 ): set_seed(4_2 ) snake_case__ : Any = RegressionModel() snake_case__ : List[Any] = deepcopy(A ) snake_case__ : Tuple = RegressionDataset(length=A ) snake_case__ : List[str] = DataLoader(A , batch_size=A ) model.to(accelerator.device ) snake_case__ , snake_case__ : Dict = accelerator.prepare(A , A ) return model, ddp_model, dataloader def lowercase__( A , A=False ): snake_case__ : str = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased' ) snake_case__ : str = load_dataset('glue' , 'mrpc' , split='validation' ) def tokenize_function(A ): snake_case__ : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=A , max_length=A ) return outputs with accelerator.main_process_first(): snake_case__ : str = dataset.map( A , batched=A , remove_columns=['idx', 'sentence1', 'sentence2'] , ) snake_case__ : Union[str, Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(A ): if use_longest: return tokenizer.pad(A , padding='longest' , return_tensors='pt' ) return tokenizer.pad(A , padding='max_length' , max_length=1_2_8 , return_tensors='pt' ) return DataLoader(A , shuffle=A , collate_fn=A , batch_size=1_6 ) def lowercase__( A , A ): snake_case__ : Tuple = Accelerator(dispatch_batches=A , split_batches=A ) snake_case__ : int = get_dataloader(A , not dispatch_batches ) snake_case__ : str = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=A ) snake_case__ , snake_case__ : Optional[Any] = accelerator.prepare(A , A ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowercase__( A , A , A ): snake_case__ : int = [] for batch in dataloader: snake_case__ , snake_case__ : Optional[int] = batch.values() with torch.no_grad(): snake_case__ : Optional[int] = model(A ) snake_case__ , snake_case__ : int = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) snake_case__ , snake_case__ : Dict = [], [] for logit, targ in logits_and_targets: logits.append(A ) targs.append(A ) snake_case__ , snake_case__ : Union[str, Any] = torch.cat(A ), torch.cat(A ) return logits, targs def lowercase__( A , A=8_2 , A=False , A=False , A=1_6 ): snake_case__ , snake_case__ , snake_case__ : List[str] = get_basic_setup(A , A , A ) snake_case__ , snake_case__ : List[Any] = generate_predictions(A , A , A ) assert ( len(A ) == num_samples ), f'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(A )}''' def lowercase__( A = False , A = False ): snake_case__ : Optional[Any] = evaluate.load('glue' , 'mrpc' ) snake_case__ , snake_case__ : Optional[Any] = get_mrpc_setup(A , A ) # First do baseline snake_case__ , snake_case__ , snake_case__ : Optional[Any] = setup['no'] model.to(A ) model.eval() for batch in dataloader: batch.to(A ) with torch.inference_mode(): snake_case__ : Optional[Any] = model(**A ) snake_case__ : Optional[Any] = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=A , references=batch['labels'] ) snake_case__ : str = metric.compute() # Then do distributed snake_case__ , snake_case__ , snake_case__ : Optional[Any] = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): snake_case__ : Union[str, Any] = model(**A ) snake_case__ : str = outputs.logits.argmax(dim=-1 ) snake_case__ : Optional[int] = batch['labels'] snake_case__ , snake_case__ : Tuple = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=A , references=A ) snake_case__ : str = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), f'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowercase__( ): snake_case__ : Union[str, Any] = Accelerator(split_batches=A , dispatch_batches=A ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''' ) test_mrpc(A , A ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: snake_case__ : Optional[int] = Accelerator(split_batches=A , dispatch_batches=A ) if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''' ) test_torch_metrics(A , 9_9 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**' ) snake_case__ : Dict = Accelerator() test_torch_metrics(A , 5_1_2 ) accelerator.state._reset_state() def lowercase__( A ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
303
from math import ceil def lowercase__( A = 1_0_0_1 ): snake_case__ : Dict = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): snake_case__ : str = 2 * i + 1 snake_case__ : Any = 2 * i snake_case__ : List[Any] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: lowerCamelCase : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number')
303
1
'''simple docstring''' class __UpperCAmelCase : def __init__( self ): """simple docstring""" _snake_case = {} def lowerCamelCase ( self ): """simple docstring""" print(self.vertex ) for i in self.vertex: print(_UpperCAmelCase , ' -> ' , ' -> '.join([str(_UpperCAmelCase ) for j in self.vertex[i]] ) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" if from_vertex in self.vertex: self.vertex[from_vertex].append(_UpperCAmelCase ) else: # else make a new vertex _snake_case = [to_vertex] def lowerCamelCase ( self ): """simple docstring""" _snake_case = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(_UpperCAmelCase , _UpperCAmelCase ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = True print(_UpperCAmelCase , end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": lowercase : Union[str, Any] = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("DFS:") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
495
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class lowercase_ ( UpperCamelCase__): """simple docstring""" def __init__( self , _UpperCAmelCase ): """simple docstring""" a_ = data def __iter__( self ): """simple docstring""" for element in self.data: yield element def lowerCamelCase_ ( UpperCAmelCase__=True ): """simple docstring""" a_ = Accelerator(even_batches=UpperCAmelCase__ ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = False ): """simple docstring""" if iterable: a_ = DummyIterableDataset(torch.as_tensor(range(UpperCAmelCase__ ) ) ) else: a_ = TensorDataset(torch.as_tensor(range(UpperCAmelCase__ ) ) ) a_ = DataLoader(UpperCAmelCase__ , batch_size=UpperCAmelCase__ ) a_ = accelerator.prepare(UpperCAmelCase__ ) return dl def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ): """simple docstring""" a_ = create_dataloader(accelerator=UpperCAmelCase__ , dataset_size=UpperCAmelCase__ , batch_size=UpperCAmelCase__ ) a_ = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator(even_batches=UpperCAmelCase__ ) verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator(even_batches=UpperCAmelCase__ ) a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) a_ = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(UpperCAmelCase__ ): a_ = ddp_model(batch[0].float() ) a_ = output.sum() loss.backward() batch_idxs.append(UpperCAmelCase__ ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def lowerCamelCase_ ( UpperCAmelCase__ ): """simple docstring""" with warnings.catch_warnings(record=UpperCAmelCase__ ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , UpperCAmelCase__ ) assert "only supported for multi-GPU" in str(w[-1].message ) def lowerCamelCase_ ( ): """simple docstring""" a_ = True a_ = False a_ = create_accelerator(even_batches=UpperCAmelCase__ ) a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): a_ = train_dl.batch_sampler.even_batches a_ = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def lowerCamelCase_ ( ): """simple docstring""" a_ = True a_ = False a_ = create_accelerator(even_batches=UpperCAmelCase__ ) a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=UpperCAmelCase__ ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): a_ = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator() a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=UpperCAmelCase__ ) with warnings.catch_warnings(record=UpperCAmelCase__ ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): pass assert issubclass(w[-1].category , UpperCAmelCase__ ) assert "only supported for map-style datasets" in str(w[-1].message ) def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) a_ = accelerator.state.distributed_type a_ = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(UpperCAmelCase__ ) a_ = original_state if __name__ == "__main__": main()
483
0
import logging import os import threading import time try: import warnings except ImportError: __lowerCamelCase : str = None try: import msvcrt except ImportError: __lowerCamelCase : str = None try: import fcntl except ImportError: __lowerCamelCase : List[Any] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: __lowerCamelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ __lowerCamelCase : str = [ """Timeout""", """BaseFileLock""", """WindowsFileLock""", """UnixFileLock""", """SoftFileLock""", """FileLock""", ] __lowerCamelCase : Union[str, Any] = """3.0.12""" __lowerCamelCase : Any = None def A_ ( ) -> List[Any]: global _logger UpperCamelCase : Any = _logger or logging.getLogger(__name__ ) return _logger class A__ ( __snake_case ): def __init__( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = lock_file return None def __str__( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = F"""The file lock '{self.lock_file}' could not be acquired.""" return temp class A__ : def __init__( self , A_ ): '''simple docstring''' UpperCamelCase : Dict = lock return None def __enter__( self ): '''simple docstring''' return self.lock def __exit__( self , A_ , A_ , A_ ): '''simple docstring''' self.lock.release() return None class A__ : def __init__( self , A_ , A_=-1 , A_=None ): '''simple docstring''' UpperCamelCase : List[Any] = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long UpperCamelCase : Dict = self.hash_filename_if_too_long(A_ , A_ ) # The path to the lock file. UpperCamelCase : List[Any] = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. UpperCamelCase : Tuple = None # The default timeout value. UpperCamelCase : Optional[Any] = timeout # We use this lock primarily for the lock counter. UpperCamelCase : Union[str, Any] = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. UpperCamelCase : Dict = 0 return None @property def __UpperCamelCase( self ): '''simple docstring''' return self._lock_file @property def __UpperCamelCase( self ): '''simple docstring''' return self._timeout @timeout.setter def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Dict = float(A_ ) return None def __UpperCamelCase( self ): '''simple docstring''' raise NotImplementedError() def __UpperCamelCase( self ): '''simple docstring''' raise NotImplementedError() @property def __UpperCamelCase( self ): '''simple docstring''' return self._lock_file_fd is not None def __UpperCamelCase( self , A_=None , A_=0.05 ): '''simple docstring''' if timeout is None: UpperCamelCase : Optional[Any] = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 UpperCamelCase : Dict = id(self ) UpperCamelCase : List[str] = self._lock_file UpperCamelCase : int = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(F"""Attempting to acquire lock {lock_id} on {lock_filename}""" ) self._acquire() if self.is_locked: logger().debug(F"""Lock {lock_id} acquired on {lock_filename}""" ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(F"""Timeout on acquiring lock {lock_id} on {lock_filename}""" ) raise Timeout(self._lock_file ) else: logger().debug( F"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...""" ) time.sleep(A_ ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: UpperCamelCase : List[Any] = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def __UpperCamelCase( self , A_=False ): '''simple docstring''' with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: UpperCamelCase : List[Any] = id(self ) UpperCamelCase : Dict = self._lock_file logger().debug(F"""Attempting to release lock {lock_id} on {lock_filename}""" ) self._release() UpperCamelCase : Dict = 0 logger().debug(F"""Lock {lock_id} released on {lock_filename}""" ) return None def __enter__( self ): '''simple docstring''' self.acquire() return self def __exit__( self , A_ , A_ , A_ ): '''simple docstring''' self.release() return None def __del__( self ): '''simple docstring''' self.release(force=A_ ) return None def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Tuple = os.path.basename(A_ ) if len(A_ ) > max_length and max_length > 0: UpperCamelCase : Optional[int] = os.path.dirname(A_ ) UpperCamelCase : int = str(hash(A_ ) ) UpperCamelCase : Any = filename[: max_length - len(A_ ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(A_ , A_ ) else: return path class A__ ( __snake_case ): def __init__( self , A_ , A_=-1 , A_=None ): '''simple docstring''' from .file_utils import relative_to_absolute_path super().__init__(A_ , timeout=A_ , max_filename_length=A_ ) UpperCamelCase : List[Any] = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: UpperCamelCase : str = os.open(self._lock_file , A_ ) except OSError: pass else: try: msvcrt.locking(A_ , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(A_ ) else: UpperCamelCase : Optional[Any] = fd return None def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = self._lock_file_fd UpperCamelCase : str = None msvcrt.locking(A_ , msvcrt.LK_UNLCK , 1 ) os.close(A_ ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class A__ ( __snake_case ): def __init__( self , A_ , A_=-1 , A_=None ): '''simple docstring''' UpperCamelCase : Tuple = os.statvfs(os.path.dirname(A_ ) ).f_namemax super().__init__(A_ , timeout=A_ , max_filename_length=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = os.O_RDWR | os.O_CREAT | os.O_TRUNC UpperCamelCase : int = os.open(self._lock_file , A_ ) try: fcntl.flock(A_ , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(A_ ) else: UpperCamelCase : List[str] = fd return None def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self._lock_file_fd UpperCamelCase : List[Any] = None fcntl.flock(A_ , fcntl.LOCK_UN ) os.close(A_ ) return None class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: UpperCamelCase : Optional[int] = os.open(self._lock_file , A_ ) except OSError: pass else: UpperCamelCase : Tuple = fd return None def __UpperCamelCase( self ): '''simple docstring''' os.close(self._lock_file_fd ) UpperCamelCase : str = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None __lowerCamelCase : Dict = None if msvcrt: __lowerCamelCase : Any = WindowsFileLock elif fcntl: __lowerCamelCase : Any = UnixFileLock else: __lowerCamelCase : int = SoftFileLock if warnings is not None: warnings.warn("""only soft file lock is available""")
38
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer __lowerCamelCase : Dict = logging.get_logger(__name__) __lowerCamelCase : Union[str, Any] = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } __lowerCamelCase : Dict = { """vocab_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json""" }, """merges_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt""" }, """tokenizer_config_file""": { """facebook/blenderbot_small-90M""": ( """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json""" ) }, } __lowerCamelCase : Tuple = { """facebook/blenderbot_small-90M""": 512, } class A__ ( __snake_case ): _UpperCAmelCase :Union[str, Any] = VOCAB_FILES_NAMES _UpperCAmelCase :Dict = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase :List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase :Optional[Any] = BlenderbotSmallTokenizer def __init__( self , A_=None , A_=None , A_="<|endoftext|>" , A_="<|endoftext|>" , A_="<|endoftext|>" , A_=False , A_=True , **A_ , ): '''simple docstring''' super().__init__( ByteLevelBPETokenizer( vocab=A_ , merges=A_ , add_prefix_space=A_ , trim_offsets=A_ , ) , bos_token=A_ , eos_token=A_ , unk_token=A_ , **A_ , ) UpperCamelCase : Union[str, Any] = add_prefix_space def __UpperCamelCase( self , A_ , A_=None ): '''simple docstring''' UpperCamelCase : Dict = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __UpperCamelCase( self , A_ , A_ = None ): '''simple docstring''' UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
38
1
'''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 ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : Dict = '''char''' A : Any = '''bpe''' A : Dict = '''wp''' UpperCamelCase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : List[Any] = ['''image_processor''', '''char_tokenizer'''] A : int = '''ViTImageProcessor''' A : List[str] = '''MgpstrTokenizer''' def __init__( self, A=None, A=None, **A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = 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, ) SCREAMING_SNAKE_CASE : str = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE : Optional[Any] = 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`.' ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained('gpt2' ) SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(A, A ) def __call__( self, A=None, A=None, A=None, **A ): '''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: SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor(A, return_tensors=A, **A ) if text is not None: SCREAMING_SNAKE_CASE : int = self.char_tokenizer(A, return_tensors=A, **A ) if text is None: return inputs elif images is None: return encodings else: SCREAMING_SNAKE_CASE : Any = encodings['input_ids'] return inputs def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = sequences SCREAMING_SNAKE_CASE : List[str] = char_preds.size(0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self._decode_helper(A, 'char' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self._decode_helper(A, 'bpe' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self._decode_helper(A, 'wp' ) SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : Tuple = [] for i in range(A ): SCREAMING_SNAKE_CASE : str = [char_scores[i], bpe_scores[i], wp_scores[i]] SCREAMING_SNAKE_CASE : Dict = [char_strs[i], bpe_strs[i], wp_strs[i]] SCREAMING_SNAKE_CASE : List[str] = scores.index(max(A ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) SCREAMING_SNAKE_CASE : List[Any] = {} SCREAMING_SNAKE_CASE : int = final_strs SCREAMING_SNAKE_CASE : Any = final_scores SCREAMING_SNAKE_CASE : Dict = char_strs SCREAMING_SNAKE_CASE : Any = bpe_strs SCREAMING_SNAKE_CASE : Union[str, Any] = wp_strs return out def UpperCamelCase_ ( self, A, A ): '''simple docstring''' if format == DecodeType.CHARACTER: SCREAMING_SNAKE_CASE : List[Any] = self.char_decode SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : str = '[s]' elif format == DecodeType.BPE: SCREAMING_SNAKE_CASE : str = self.bpe_decode SCREAMING_SNAKE_CASE : str = 2 SCREAMING_SNAKE_CASE : List[str] = '#' elif format == DecodeType.WORDPIECE: SCREAMING_SNAKE_CASE : Any = self.wp_decode SCREAMING_SNAKE_CASE : Tuple = 102 SCREAMING_SNAKE_CASE : List[Any] = '[SEP]' else: raise ValueError(F"Format {format} is not supported." ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = [], [] SCREAMING_SNAKE_CASE : Union[str, Any] = pred_logits.size(0 ) SCREAMING_SNAKE_CASE : Any = pred_logits.size(1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = pred_logits.topk(1, dim=-1, largest=A, sorted=A ) SCREAMING_SNAKE_CASE : Optional[int] = preds_index.view(-1, A )[:, 1:] SCREAMING_SNAKE_CASE : List[Any] = decoder(A ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.softmax(A, dim=2 ).max(dim=2 ) SCREAMING_SNAKE_CASE : Dict = preds_max_prob[:, 1:] for index in range(A ): SCREAMING_SNAKE_CASE : Optional[int] = preds_str[index].find(A ) SCREAMING_SNAKE_CASE : List[Any] = preds_str[index][:pred_eos] SCREAMING_SNAKE_CASE : Dict = preds_index[index].cpu().tolist() SCREAMING_SNAKE_CASE : Union[str, Any] = pred_index.index(A ) if eos_token in pred_index else -1 SCREAMING_SNAKE_CASE : Optional[int] = preds_max_prob[index][: pred_eos_index + 1] SCREAMING_SNAKE_CASE : Optional[int] = 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 UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [seq.replace(' ', '' ) for seq in self.char_tokenizer.batch_decode(A )] return decode_strs def UpperCamelCase_ ( self, A ): '''simple docstring''' return self.bpe_tokenizer.batch_decode(A ) def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [seq.replace(' ', '' ) for seq in self.wp_tokenizer.batch_decode(A )] return decode_strs
28
'''simple docstring''' import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _A ( A ,A ) -> str: lowercase : Optional[int] = old_name if "patch_embed" in old_name: lowercase , lowercase , lowercase : Tuple = old_name.split("." ) if layer == "0": lowercase : int = old_name.replace("0" ,"convolution1" ) elif layer == "1": lowercase : List[str] = old_name.replace("1" ,"batchnorm_before" ) elif layer == "3": lowercase : Dict = old_name.replace("3" ,"convolution2" ) else: lowercase : Union[str, Any] = old_name.replace("4" ,"batchnorm_after" ) if "network" in old_name and re.search(r"\d\.\d" ,A ): lowercase : List[str] = r"\b\d{2}\b" if bool(re.search(A ,A ) ): lowercase : str = re.search(r"\d\.\d\d." ,A ).group() else: lowercase : int = re.search(r"\d\.\d." ,A ).group() if int(match[0] ) < 6: lowercase : str = old_name.replace(A ,"" ) lowercase : List[str] = trimmed_name.replace("network" ,match[0] + ".meta4D_layers.blocks." + match[2:-1] ) lowercase : Optional[Any] = "intermediate_stages." + trimmed_name else: lowercase : str = old_name.replace(A ,"" ) if int(match[2] ) < num_meta4D_last_stage: lowercase : Optional[int] = trimmed_name.replace("network" ,"meta4D_layers.blocks." + match[2] ) else: lowercase : List[Any] = str(int(match[2] ) - num_meta4D_last_stage ) lowercase : List[Any] = trimmed_name.replace("network" ,"meta3D_layers.blocks." + layer_index ) if "norm1" in old_name: lowercase : str = trimmed_name.replace("norm1" ,"layernorm1" ) elif "norm2" in old_name: lowercase : Optional[Any] = trimmed_name.replace("norm2" ,"layernorm2" ) elif "fc1" in old_name: lowercase : Optional[int] = trimmed_name.replace("fc1" ,"linear_in" ) elif "fc2" in old_name: lowercase : str = trimmed_name.replace("fc2" ,"linear_out" ) lowercase : Dict = "last_stage." + trimmed_name elif "network" in old_name and re.search(r".\d." ,A ): lowercase : Union[str, Any] = old_name.replace("network" ,"intermediate_stages" ) if "fc" in new_name: lowercase : Any = new_name.replace("fc" ,"convolution" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): lowercase : Optional[Any] = new_name.replace("norm1" ,"batchnorm_before" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): lowercase : List[str] = new_name.replace("norm2" ,"batchnorm_after" ) if "proj" in new_name: lowercase : Optional[int] = new_name.replace("proj" ,"projection" ) if "dist_head" in new_name: lowercase : Tuple = new_name.replace("dist_head" ,"distillation_classifier" ) elif "head" in new_name: lowercase : Tuple = new_name.replace("head" ,"classifier" ) elif "patch_embed" in new_name: lowercase : Optional[int] = "efficientformer." + new_name elif new_name == "norm.weight" or new_name == "norm.bias": lowercase : str = new_name.replace("norm" ,"layernorm" ) lowercase : List[Any] = "efficientformer." + new_name else: lowercase : Optional[Any] = "efficientformer.encoder." + new_name return new_name def _A ( A ,A ) -> Optional[Any]: for key in checkpoint.copy().keys(): lowercase : List[str] = checkpoint.pop(A ) lowercase : int = val return checkpoint def _A ( ) -> Optional[int]: lowercase : str = "http://images.cocodataset.org/val2017/000000039769.jpg" lowercase : Optional[Any] = Image.open(requests.get(A ,stream=A ).raw ) return image def _A ( A ,A ,A ,A ) -> List[Any]: lowercase : Optional[int] = torch.load(A ,map_location="cpu" )["model"] lowercase : int = EfficientFormerConfig.from_json_file(A ) lowercase : Tuple = EfficientFormerForImageClassificationWithTeacher(A ) lowercase : int = "_".join(checkpoint_path.split("/" )[-1].split("." )[0].split("_" )[:-1] ) lowercase : Optional[int] = config.depths[-1] - config.num_metaad_blocks + 1 lowercase : int = convert_torch_checkpoint(A ,A ) model.load_state_dict(A ) model.eval() lowercase : List[Any] = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } # prepare image lowercase : Tuple = prepare_img() lowercase : Optional[int] = 2_5_6 lowercase : str = 2_2_4 lowercase : List[str] = EfficientFormerImageProcessor( size={"shortest_edge": image_size} ,crop_size={"height": crop_size, "width": crop_size} ,resample=pillow_resamplings["bicubic"] ,) lowercase : Union[str, Any] = processor(images=A ,return_tensors="pt" ).pixel_values # original processing pipeline lowercase : Tuple = Compose( [ Resize(A ,interpolation=pillow_resamplings["bicubic"] ), CenterCrop(A ), ToTensor(), Normalize(A ,A ), ] ) lowercase : List[Any] = image_transforms(A ).unsqueeze(0 ) assert torch.allclose(A ,A ) lowercase : Union[str, Any] = model(A ) lowercase : Any = outputs.logits lowercase : List[str] = (1, 1_0_0_0) if "l1" in model_name: lowercase : Any = torch.Tensor( [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328] ) assert torch.allclose(logits[0, :1_0] ,A ,atol=1e-3 ) assert logits.shape == expected_shape elif "l3" in model_name: lowercase : List[Any] = torch.Tensor( [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127] ) assert torch.allclose(logits[0, :1_0] ,A ,atol=1e-3 ) assert logits.shape == expected_shape elif "l7" in model_name: lowercase : Optional[int] = torch.Tensor( [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878] ) assert logits.shape == expected_shape else: raise ValueError( F'''Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7''' ) # Save Checkpoints Path(A ).mkdir(exist_ok=A ) model.save_pretrained(A ) print(F'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) processor.save_pretrained(A ) print(F'''Processor successfuly saved at {pytorch_dump_path}''' ) if push_to_hub: print("Pushing model to the hub..." ) model.push_to_hub( repo_id=F'''Bearnardd/{pytorch_dump_path}''' ,commit_message="Add model" ,use_temp_dir=A ,) processor.push_to_hub( repo_id=F'''Bearnardd/{pytorch_dump_path}''' ,commit_message="Add image processor" ,use_temp_dir=A ,) if __name__ == "__main__": lowerCAmelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--pytorch_model_path""", default=None, type=str, required=True, help="""Path to EfficientFormer pytorch checkpoint.""", ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The json file for EfficientFormer model config.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) parser.set_defaults(push_to_hub=True) lowerCAmelCase : Optional[int] = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
372
0
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration __a = 5_0_0_0_0_0 __a , __a = os.path.split(__file__) __a = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def a ( snake_case__: datasets.Dataset , **snake_case__: Dict ): '''simple docstring''' lowercase_ = dataset.map(**snake_case__ ) @get_duration def a ( snake_case__: datasets.Dataset , **snake_case__: Any ): '''simple docstring''' lowercase_ = dataset.filter(**snake_case__ ) def a ( ): '''simple docstring''' lowercase_ = {'''num examples''': SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ = datasets.Features({'''text''': datasets.Value('''string''' ), '''numbers''': datasets.Value('''float32''' )} ) lowercase_ = generate_example_dataset( os.path.join(snake_case__ , '''dataset.arrow''' ) , snake_case__ , num_examples=snake_case__ ) lowercase_ = transformers.AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=snake_case__ ) def tokenize(snake_case__: List[str] ): return tokenizer(examples['''text'''] ) lowercase_ = map(snake_case__ ) lowercase_ = map(snake_case__ , batched=snake_case__ ) lowercase_ = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type='''numpy''' ): lowercase_ = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type='''pandas''' ): lowercase_ = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type='''torch''' , columns='''numbers''' ): lowercase_ = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type='''tensorflow''' , columns='''numbers''' ): lowercase_ = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) lowercase_ = map(snake_case__ , function=snake_case__ , batched=snake_case__ ) lowercase_ = filter(snake_case__ ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(snake_case__ , '''wb''' ) as f: f.write(json.dumps(snake_case__ ).encode('''utf-8''' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
409
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) # TODO Update this __a = { 'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json', # See all ESM models at https://huggingface.co/models?filter=esm } class lowercase__( UpperCAmelCase ): """simple docstring""" a :str = 'esm' def __init__( self : int , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : Any=7_6_8 , SCREAMING_SNAKE_CASE_ : List[str]=1_2 , SCREAMING_SNAKE_CASE_ : int=1_2 , SCREAMING_SNAKE_CASE_ : Dict=3_0_7_2 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_0_2_6 , SCREAMING_SNAKE_CASE_ : List[str]=0.02 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE_ : int="absolute" , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : Tuple=False , SCREAMING_SNAKE_CASE_ : Tuple=False , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : int=None , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> Union[str, Any]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , mask_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowercase_ = vocab_size lowercase_ = hidden_size lowercase_ = num_hidden_layers lowercase_ = num_attention_heads lowercase_ = intermediate_size lowercase_ = hidden_dropout_prob lowercase_ = attention_probs_dropout_prob lowercase_ = max_position_embeddings lowercase_ = initializer_range lowercase_ = layer_norm_eps lowercase_ = position_embedding_type lowercase_ = use_cache lowercase_ = emb_layer_norm_before lowercase_ = token_dropout lowercase_ = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) lowercase_ = EsmFoldConfig() elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase_ = EsmFoldConfig(**SCREAMING_SNAKE_CASE_ ) lowercase_ = esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) lowercase_ = get_default_vocab_list() else: lowercase_ = vocab_list else: lowercase_ = None lowercase_ = None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , SCREAMING_SNAKE_CASE_ ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def _lowercase ( self : Any ) -> str: lowercase_ = super().to_dict() if isinstance(self.esmfold_config , SCREAMING_SNAKE_CASE_ ): lowercase_ = self.esmfold_config.to_dict() return output @dataclass class lowercase__: """simple docstring""" a :str = None a :bool = True a :bool = False a :bool = False a :bool = False a :float = 0 a :bool = True a :bool = False a :int = 128 a :"TrunkConfig" = None def _lowercase ( self : Optional[Any] ) -> List[str]: if self.trunk is None: lowercase_ = TrunkConfig() elif isinstance(self.trunk , SCREAMING_SNAKE_CASE_ ): lowercase_ = TrunkConfig(**self.trunk ) def _lowercase ( self : Dict ) -> int: lowercase_ = asdict(self ) lowercase_ = self.trunk.to_dict() return output @dataclass class lowercase__: """simple docstring""" a :int = 48 a :int = 1_024 a :int = 128 a :int = 32 a :int = 32 a :int = 32 a :float = 0 a :float = 0 a :bool = False a :int = 4 a :Optional[int] = 128 a :"StructureModuleConfig" = None def _lowercase ( self : Tuple ) -> Dict: if self.structure_module is None: lowercase_ = StructureModuleConfig() elif isinstance(self.structure_module , SCREAMING_SNAKE_CASE_ ): lowercase_ = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f'''`max_recycles` should be positive, got {self.max_recycles}.''' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' f''' {self.sequence_state_dim} and {self.sequence_state_dim}.''' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' f''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.''' ) lowercase_ = self.sequence_state_dim // self.sequence_head_width lowercase_ = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' f''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.''' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' f''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.''' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.''' ) if self.dropout >= 0.4: raise ValueError(f'''`dropout` should not be greater than 0.4, got {self.dropout}.''' ) def _lowercase ( self : Any ) -> Dict: lowercase_ = asdict(self ) lowercase_ = self.structure_module.to_dict() return output @dataclass class lowercase__: """simple docstring""" a :int = 384 a :int = 128 a :int = 16 a :int = 128 a :int = 12 a :int = 4 a :int = 8 a :float = 0.1 a :int = 8 a :int = 1 a :int = 2 a :int = 7 a :int = 10 a :float = 1e-8 a :float = 1e5 def _lowercase ( self : Tuple ) -> Tuple: return asdict(self ) def a ( ): '''simple docstring''' return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
409
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE :int = 16 SCREAMING_SNAKE_CASE :Any = 32 def UpperCAmelCase ( a_ , a_ = 1_6 ) -> List[Any]: """simple docstring""" __A = AutoTokenizer.from_pretrained("bert-base-cased" ) __A = load_dataset("glue" , "mrpc" ) def tokenize_function(a_ ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=a_ , max_length=a_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __A = datasets.map( a_ , batched=a_ , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __A = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(a_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __A = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __A = 1_6 elif accelerator.mixed_precision != "no": __A = 8 else: __A = None return tokenizer.pad( a_ , padding="longest" , max_length=a_ , pad_to_multiple_of=a_ , return_tensors="pt" , ) # Instantiate dataloaders. __A = DataLoader( tokenized_datasets["train"] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) __A = DataLoader( tokenized_datasets["validation"] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE :Any = mocked_dataloaders # noqa: F811 def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , a_ ) == "1": __A = 2 # New Code # __A = int(args.gradient_accumulation_steps ) __A = int(args.local_sgd_steps ) # Initialize accelerator __A = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=a_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __A = config["lr"] __A = int(config["num_epochs"] ) __A = int(config["seed"] ) __A = int(config["batch_size"] ) __A = evaluate.load("glue" , "mrpc" ) set_seed(a_ ) __A , __A = get_dataloaders(a_ , a_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __A = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=a_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __A = model.to(accelerator.device ) # Instantiate optimizer __A = AdamW(params=model.parameters() , lr=a_ ) # Instantiate scheduler __A = get_linear_schedule_with_warmup( optimizer=a_ , num_warmup_steps=1_0_0 , num_training_steps=(len(a_ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __A , __A , __A , __A , __A = accelerator.prepare( a_ , a_ , a_ , a_ , a_ ) # Now we train the model for epoch in range(a_ ): model.train() with LocalSGD( accelerator=a_ , model=a_ , local_sgd_steps=a_ , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(a_ ): __A = model(**a_ ) __A = output.loss accelerator.backward(a_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __A = model(**a_ ) __A = outputs.logits.argmax(dim=-1 ) __A , __A = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=a_ , references=a_ , ) __A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , a_ ) def UpperCAmelCase ( ) -> int: """simple docstring""" __A = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=a_ , default=a_ , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=a_ , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument( "--local_sgd_steps" , type=a_ , default=8 , help="Number of local SGD steps or None to disable local SGD" ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) __A = parser.parse_args() __A = {"lr": 2E-5, "num_epochs": 3, "seed": 4_2, "batch_size": 1_6} training_function(a_ , a_ ) if __name__ == "__main__": main()
55
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) A_ = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn.grep_linear": "encoder.layers.*.attention.gru_rel_pos_linear", "self_attn.relative_attention_bias": "encoder.layers.*.attention.rel_attn_embed", "self_attn.grep_a": "encoder.layers.*.attention.gru_rel_pos_const", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "ctc_proj", "mask_emb": "masked_spec_embed", } A_ = [ "ctc_proj", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _UpperCamelCase ( A , A , A , A , A ): for attribute in key.split("." ): UpperCamelCase_ =getattr(A , A ) if weight_type is not None: UpperCamelCase_ =getattr(A , A ).shape else: UpperCamelCase_ =hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCamelCase_ =value elif weight_type == "weight_g": UpperCamelCase_ =value elif weight_type == "weight_v": UpperCamelCase_ =value elif weight_type == "bias": UpperCamelCase_ =value else: UpperCamelCase_ =value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _UpperCamelCase ( A , A ): UpperCamelCase_ =[] UpperCamelCase_ =fairseq_model.state_dict() UpperCamelCase_ =hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase_ =False if "conv_layers" in name: load_conv_layer( A , A , A , A , hf_model.config.feat_extract_norm == "group" , ) UpperCamelCase_ =True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: UpperCamelCase_ =True if "*" in mapped_key: UpperCamelCase_ =name.split(A )[0].split("." )[-2] UpperCamelCase_ =mapped_key.replace("*" , A ) if "weight_g" in name: UpperCamelCase_ ="weight_g" elif "weight_v" in name: UpperCamelCase_ ="weight_v" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase_ ="bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase_ ="weight" else: UpperCamelCase_ =None set_recursively(A , A , A , A , A ) continue if not is_used: unused_weights.append(A ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _UpperCamelCase ( A , A , A , A , A ): UpperCamelCase_ =full_name.split("conv_layers." )[-1] UpperCamelCase_ =name.split("." ) UpperCamelCase_ =int(items[0] ) UpperCamelCase_ =int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCamelCase_ =value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCamelCase_ =value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCamelCase_ =value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCamelCase_ =value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(A ) @torch.no_grad() def _UpperCamelCase ( A , A , A=None ): # load the pre-trained checkpoints UpperCamelCase_ =torch.load(A ) UpperCamelCase_ =WavLMConfigOrig(checkpoint["cfg"] ) UpperCamelCase_ =WavLMOrig(A ) model.load_state_dict(checkpoint["model"] ) model.eval() if config_path is not None: UpperCamelCase_ =WavLMConfig.from_pretrained(A ) else: UpperCamelCase_ =WavLMConfig() UpperCamelCase_ =WavLMModel(A ) recursively_load_weights(A , A ) hf_wavlm.save_pretrained(A ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") A_ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
391
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""", } class a__ ( _lowercase ): __magic_name__ : Optional[Any] = "nllb-moe" __magic_name__ : Optional[Any] = ["past_key_values"] __magic_name__ : Optional[int] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__(self : int, __UpperCAmelCase : Tuple=128112, __UpperCAmelCase : Any=1024, __UpperCAmelCase : Optional[Any]=12, __UpperCAmelCase : Optional[int]=4096, __UpperCAmelCase : Any=16, __UpperCAmelCase : Any=12, __UpperCAmelCase : Optional[Any]=4096, __UpperCAmelCase : Optional[int]=16, __UpperCAmelCase : List[Any]=0.05, __UpperCAmelCase : Dict=0.05, __UpperCAmelCase : Dict=True, __UpperCAmelCase : List[Any]=True, __UpperCAmelCase : Any="relu", __UpperCAmelCase : Union[str, Any]=1024, __UpperCAmelCase : Optional[int]=0.1, __UpperCAmelCase : Tuple=0.1, __UpperCAmelCase : List[Any]=0.0, __UpperCAmelCase : Optional[int]=0.02, __UpperCAmelCase : Tuple=2, __UpperCAmelCase : int=True, __UpperCAmelCase : int=False, __UpperCAmelCase : int="float32", __UpperCAmelCase : Optional[Any]=False, __UpperCAmelCase : List[str]=128, __UpperCAmelCase : Dict=64, __UpperCAmelCase : Dict=4, __UpperCAmelCase : Optional[Any]=4, __UpperCAmelCase : Optional[Any]=0.001, __UpperCAmelCase : Optional[Any]=0.001, __UpperCAmelCase : Optional[Any]="all", __UpperCAmelCase : List[str]=False, __UpperCAmelCase : Dict=False, __UpperCAmelCase : Any=1.0, __UpperCAmelCase : Dict=0.2, __UpperCAmelCase : int=1, __UpperCAmelCase : Union[str, Any]=0, __UpperCAmelCase : Any=2, __UpperCAmelCase : Union[str, Any]=False, **__UpperCAmelCase : Dict, ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : int = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = d_model SCREAMING_SNAKE_CASE : Dict = encoder_ffn_dim SCREAMING_SNAKE_CASE : int = encoder_layers SCREAMING_SNAKE_CASE : str = encoder_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = decoder_ffn_dim SCREAMING_SNAKE_CASE : str = decoder_layers SCREAMING_SNAKE_CASE : Dict = decoder_attention_heads SCREAMING_SNAKE_CASE : Dict = dropout SCREAMING_SNAKE_CASE : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE : Dict = activation_dropout SCREAMING_SNAKE_CASE : List[str] = activation_function SCREAMING_SNAKE_CASE : Union[str, Any] = init_std SCREAMING_SNAKE_CASE : Any = encoder_layerdrop SCREAMING_SNAKE_CASE : Optional[int] = decoder_layerdrop SCREAMING_SNAKE_CASE : Dict = use_cache SCREAMING_SNAKE_CASE : Optional[Any] = encoder_layers SCREAMING_SNAKE_CASE : Optional[Any] = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE : List[str] = router_z_loss_coef SCREAMING_SNAKE_CASE : List[str] = router_aux_loss_coef SCREAMING_SNAKE_CASE : int = decoder_sparse_step SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_sparse_step SCREAMING_SNAKE_CASE : Union[str, Any] = num_experts SCREAMING_SNAKE_CASE : List[Any] = expert_capacity SCREAMING_SNAKE_CASE : Optional[Any] = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = router_dtype SCREAMING_SNAKE_CASE : int = router_ignore_padding_tokens SCREAMING_SNAKE_CASE : Dict = batch_prioritized_routing SCREAMING_SNAKE_CASE : Dict = second_expert_policy SCREAMING_SNAKE_CASE : Tuple = normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE : List[str] = moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE : List[Any] = moe_token_dropout SCREAMING_SNAKE_CASE : List[Any] = output_router_logits super().__init__( pad_token_id=__UpperCAmelCase, bos_token_id=__UpperCAmelCase, eos_token_id=__UpperCAmelCase, is_encoder_decoder=__UpperCAmelCase, decoder_start_token_id=__UpperCAmelCase, **__UpperCAmelCase, )
355
'''simple docstring''' import heapq import sys import numpy as np snake_case_ = tuple[int, int] class a__ : def __init__(self : int ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Tuple = set() def lowercase__ (self : Any ) -> Dict: """simple docstring""" if not self.empty(): return self.elements[0][0] else: return float('''inf''' ) def lowercase__ (self : Dict ) -> Union[str, Any]: """simple docstring""" return len(self.elements ) == 0 def lowercase__ (self : Dict, __UpperCAmelCase : int, __UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" if item not in self.set: heapq.heappush(self.elements, (priority, item) ) self.set.add(__UpperCAmelCase ) else: # update # print("update", item) SCREAMING_SNAKE_CASE : List[Any] = [] ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Any = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Any = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements, (pro, xxx) ) def lowercase__ (self : Union[str, Any], __UpperCAmelCase : Optional[Any] ) -> Optional[int]: """simple docstring""" if item in self.set: self.set.remove(__UpperCAmelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Any = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Optional[Any] = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements, (prito, yyy) ) def lowercase__ (self : Tuple ) -> Dict: """simple docstring""" return self.elements[0][1] def lowercase__ (self : Optional[Any] ) -> Tuple: """simple docstring""" ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Optional[int] = heapq.heappop(self.elements ) self.set.remove(__UpperCAmelCase ) return (priority, item) def __lowercase (_SCREAMING_SNAKE_CASE :TPos , _SCREAMING_SNAKE_CASE :TPos ): # euclidean distance SCREAMING_SNAKE_CASE : str = np.array(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE : List[Any] = np.array(_SCREAMING_SNAKE_CASE ) return np.linalg.norm(a - b ) def __lowercase (_SCREAMING_SNAKE_CASE :TPos , _SCREAMING_SNAKE_CASE :TPos ): # integer division by time variable return consistent_heuristic(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) // t def __lowercase (_SCREAMING_SNAKE_CASE :TPos , _SCREAMING_SNAKE_CASE :TPos ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def __lowercase (_SCREAMING_SNAKE_CASE :TPos , _SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :TPos , _SCREAMING_SNAKE_CASE :dict[TPos, float] ): SCREAMING_SNAKE_CASE : List[str] = g_function[start] + Wa * heuristics[i](_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return ans def __lowercase (_SCREAMING_SNAKE_CASE :Optional[Any] , _SCREAMING_SNAKE_CASE :List[str] , _SCREAMING_SNAKE_CASE :Tuple ): SCREAMING_SNAKE_CASE : Optional[int] = np.chararray((n, n) ) for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE : Tuple = '''*''' for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): if (j, (n - 1) - i) in blocks: SCREAMING_SNAKE_CASE : Tuple = '''#''' SCREAMING_SNAKE_CASE : List[Any] = '''-''' SCREAMING_SNAKE_CASE : Any = back_pointer[goal] while x != start: ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Optional[int] = x # print(x) SCREAMING_SNAKE_CASE : int = '''-''' SCREAMING_SNAKE_CASE : Dict = back_pointer[x] SCREAMING_SNAKE_CASE : int = '''-''' for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = back_pointer[goal] while x != start: print(_SCREAMING_SNAKE_CASE , end=''' ''' ) SCREAMING_SNAKE_CASE : Optional[int] = back_pointer[x] print(_SCREAMING_SNAKE_CASE ) sys.exit() def __lowercase (_SCREAMING_SNAKE_CASE :TPos ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def __lowercase (_SCREAMING_SNAKE_CASE :Union[str, Any] , _SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :List[str] , _SCREAMING_SNAKE_CASE :List[str] , _SCREAMING_SNAKE_CASE :List[str] , _SCREAMING_SNAKE_CASE :Union[str, Any] , _SCREAMING_SNAKE_CASE :Tuple , _SCREAMING_SNAKE_CASE :Optional[int] , ): for itera in range(_SCREAMING_SNAKE_CASE ): open_list[itera].remove_element(_SCREAMING_SNAKE_CASE ) # print("s", s) # print("j", j) ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Tuple = s SCREAMING_SNAKE_CASE : List[Any] = (x - 1, y) SCREAMING_SNAKE_CASE : Optional[Any] = (x + 1, y) SCREAMING_SNAKE_CASE : List[Any] = (x, y + 1) SCREAMING_SNAKE_CASE : Any = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(_SCREAMING_SNAKE_CASE ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE : Optional[int] = -1 SCREAMING_SNAKE_CASE : List[str] = float('''inf''' ) if valid(_SCREAMING_SNAKE_CASE ) and g_function[neighbours] > g_function[s] + 1: SCREAMING_SNAKE_CASE : List[str] = g_function[s] + 1 SCREAMING_SNAKE_CASE : Optional[Any] = s if neighbours not in close_list_anchor: open_list[0].put(_SCREAMING_SNAKE_CASE , key(_SCREAMING_SNAKE_CASE , 0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) if neighbours not in close_list_inad: for var in range(1 , _SCREAMING_SNAKE_CASE ): if key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) <= Wa * key( _SCREAMING_SNAKE_CASE , 0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): open_list[j].put( _SCREAMING_SNAKE_CASE , key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def __lowercase (): SCREAMING_SNAKE_CASE : Optional[int] = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list snake_case_ = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} snake_case_ = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] snake_case_ = make_common_ground() snake_case_ = blocks_blk # hyper parameters snake_case_ = 1 snake_case_ = 1 snake_case_ = 20 snake_case_ = 3 # one consistent and two other inconsistent # start and end destination snake_case_ = (0, 0) snake_case_ = (n - 1, n - 1) snake_case_ = 1 def __lowercase (_SCREAMING_SNAKE_CASE :TPos , _SCREAMING_SNAKE_CASE :TPos , _SCREAMING_SNAKE_CASE :int ): SCREAMING_SNAKE_CASE : Any = {start: 0, goal: float('''inf''' )} SCREAMING_SNAKE_CASE : Tuple = {start: -1, goal: -1} SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Union[str, Any] = set() for i in range(_SCREAMING_SNAKE_CASE ): open_list.append(PriorityQueue() ) open_list[i].put(_SCREAMING_SNAKE_CASE , key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) SCREAMING_SNAKE_CASE : list[int] = [] SCREAMING_SNAKE_CASE : list[int] = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , _SCREAMING_SNAKE_CASE ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = open_list[i].top_show() visited.add(_SCREAMING_SNAKE_CASE ) expand_state( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) close_list_inad.append(_SCREAMING_SNAKE_CASE ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: SCREAMING_SNAKE_CASE : List[Any] = open_list[0].top_show() visited.add(_SCREAMING_SNAKE_CASE ) expand_state( _SCREAMING_SNAKE_CASE , 0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) close_list_anchor.append(_SCREAMING_SNAKE_CASE ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(_SCREAMING_SNAKE_CASE ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
355
1
'''simple docstring''' import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowerCamelCase ( _A , unittest.TestCase ): snake_case_ = BertTokenizer snake_case_ = BertTokenizerFast snake_case_ = True snake_case_ = True snake_case_ = filter_non_english def _lowerCamelCase ( self ): super().setUp() lowerCAmelCase : Union[str, Any] = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowerCAmelCase : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _lowerCamelCase ( self , a_ ): lowerCAmelCase : Tuple = "UNwant\u00E9d,running" lowerCAmelCase : int = "unwanted, running" return input_text, output_text def _lowerCamelCase ( self ): lowerCAmelCase : Optional[Any] = self.tokenizer_class(self.vocab_file ) lowerCAmelCase : Optional[int] = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(a_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [9, 6, 7, 12, 10, 11] ) def _lowerCamelCase ( self ): if not self.test_rust_tokenizer: return lowerCAmelCase : Union[str, Any] = self.get_tokenizer() lowerCAmelCase : Union[str, Any] = self.get_rust_tokenizer() lowerCAmelCase : Tuple = "UNwant\u00E9d,running" lowerCAmelCase : Any = tokenizer.tokenize(a_ ) lowerCAmelCase : int = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) lowerCAmelCase : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) lowerCAmelCase : Dict = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) lowerCAmelCase : Any = self.get_rust_tokenizer() lowerCAmelCase : Optional[Any] = tokenizer.encode(a_ ) lowerCAmelCase : List[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) # With lower casing lowerCAmelCase : Any = self.get_tokenizer(do_lower_case=a_ ) lowerCAmelCase : int = self.get_rust_tokenizer(do_lower_case=a_ ) lowerCAmelCase : List[str] = "UNwant\u00E9d,running" lowerCAmelCase : str = tokenizer.tokenize(a_ ) lowerCAmelCase : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) lowerCAmelCase : Union[str, Any] = tokenizer.encode(a_ , add_special_tokens=a_ ) lowerCAmelCase : Tuple = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) lowerCAmelCase : Tuple = self.get_rust_tokenizer() lowerCAmelCase : str = tokenizer.encode(a_ ) lowerCAmelCase : List[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) def _lowerCamelCase ( self ): lowerCAmelCase : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def _lowerCamelCase ( self ): lowerCAmelCase : int = BasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _lowerCamelCase ( self ): lowerCAmelCase : Dict = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def _lowerCamelCase ( self ): lowerCAmelCase : Optional[Any] = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _lowerCamelCase ( self ): lowerCAmelCase : Dict = BasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _lowerCamelCase ( self ): lowerCAmelCase : Tuple = BasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def _lowerCamelCase ( self ): lowerCAmelCase : int = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def _lowerCamelCase ( self ): lowerCAmelCase : Any = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def _lowerCamelCase ( self ): lowerCAmelCase : Any = BasicTokenizer(do_lower_case=a_ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def _lowerCamelCase ( self ): lowerCAmelCase : str = BasicTokenizer() lowerCAmelCase : Optional[Any] = "a\n'll !!to?'d of, can't." lowerCAmelCase : Union[str, Any] = ["a", "'", "ll", "!", "!", "to", "?", "'", "d", "of", ",", "can", "'", "t", "."] self.assertListEqual(tokenizer.tokenize(a_ ) , a_ ) def _lowerCamelCase ( self ): lowerCAmelCase : Optional[Any] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] lowerCAmelCase : Optional[Any] = {} for i, token in enumerate(a_ ): lowerCAmelCase : List[str] = i lowerCAmelCase : List[Any] = WordpieceTokenizer(vocab=a_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def _lowerCamelCase ( self ): self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def _lowerCamelCase ( self ): self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def _lowerCamelCase ( self ): self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def _lowerCamelCase ( self ): lowerCAmelCase : Dict = self.get_tokenizer() lowerCAmelCase : Union[str, Any] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(a_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(a_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) @slow def _lowerCamelCase ( self ): lowerCAmelCase : Union[str, Any] = self.tokenizer_class.from_pretrained("bert-base-uncased" ) lowerCAmelCase : str = tokenizer.encode("sequence builders" , add_special_tokens=a_ ) lowerCAmelCase : int = tokenizer.encode("multi-sequence build" , add_special_tokens=a_ ) lowerCAmelCase : int = tokenizer.build_inputs_with_special_tokens(a_ ) lowerCAmelCase : List[Any] = tokenizer.build_inputs_with_special_tokens(a_ , a_ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def _lowerCamelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCAmelCase : Tuple = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) lowerCAmelCase : List[Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' lowerCAmelCase : str = tokenizer_r.encode_plus( a_ , return_attention_mask=a_ , return_token_type_ids=a_ , return_offsets_mapping=a_ , add_special_tokens=a_ , ) lowerCAmelCase : List[str] = tokenizer_r.do_lower_case if hasattr(a_ , "do_lower_case" ) else False lowerCAmelCase : Optional[Any] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def _lowerCamelCase ( self ): lowerCAmelCase : Optional[int] = ["的", "人", "有"] lowerCAmelCase : Optional[Any] = "".join(a_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCAmelCase : List[Any] = True lowerCAmelCase : int = self.tokenizer_class.from_pretrained(a_ , **a_ ) lowerCAmelCase : List[str] = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) lowerCAmelCase : Tuple = tokenizer_p.encode(a_ , add_special_tokens=a_ ) lowerCAmelCase : Any = tokenizer_r.encode(a_ , add_special_tokens=a_ ) lowerCAmelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(a_ ) lowerCAmelCase : int = tokenizer_p.convert_ids_to_tokens(a_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , a_ ) lowerCAmelCase : List[str] = False lowerCAmelCase : List[Any] = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) lowerCAmelCase : Dict = self.tokenizer_class.from_pretrained(a_ , **a_ ) lowerCAmelCase : Tuple = tokenizer_r.encode(a_ , add_special_tokens=a_ ) lowerCAmelCase : List[str] = tokenizer_p.encode(a_ , add_special_tokens=a_ ) lowerCAmelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(a_ ) lowerCAmelCase : Dict = tokenizer_p.convert_ids_to_tokens(a_ ) # it is expected that only the first Chinese character is not preceded by "##". lowerCAmelCase : Tuple = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(a_ ) ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , a_ )
525
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCAmelCase = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
525
1
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging a = logging.get_logger(__name__) a = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _a ): _a = 't5' _a = ['past_key_values'] _a = {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self : Dict , lowerCAmelCase : Optional[Any]=3_2128 , lowerCAmelCase : Tuple=512 , lowerCAmelCase : int=64 , lowerCAmelCase : Dict=2048 , lowerCAmelCase : Any=6 , lowerCAmelCase : List[str]=None , lowerCAmelCase : Tuple=8 , lowerCAmelCase : int=32 , lowerCAmelCase : int=128 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : Dict=1e-6 , lowerCAmelCase : int=1.0 , lowerCAmelCase : List[Any]="relu" , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Any=True , lowerCAmelCase : Optional[Any]=0 , lowerCAmelCase : Optional[int]=1 , **lowerCAmelCase : List[Any] , ): lowerCAmelCase = vocab_size lowerCAmelCase = d_model lowerCAmelCase = d_kv lowerCAmelCase = d_ff lowerCAmelCase = num_layers lowerCAmelCase = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase = num_heads lowerCAmelCase = relative_attention_num_buckets lowerCAmelCase = relative_attention_max_distance lowerCAmelCase = dropout_rate lowerCAmelCase = layer_norm_epsilon lowerCAmelCase = initializer_factor lowerCAmelCase = feed_forward_proj lowerCAmelCase = use_cache lowerCAmelCase = self.feed_forward_proj.split("""-""" ) lowerCAmelCase = act_info[-1] lowerCAmelCase = act_info[0] == """gated""" if len(lowerCAmelCase ) > 1 and act_info[0] != "gated" or len(lowerCAmelCase ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": lowerCAmelCase = """gelu_new""" super().__init__( pad_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , is_encoder_decoder=lowerCAmelCase , **lowerCAmelCase , ) class SCREAMING_SNAKE_CASE__ ( _a ): @property def __lowercase ( self : str ): lowerCAmelCase = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: lowerCAmelCase = """past_encoder_sequence + sequence""" lowerCAmelCase = {0: """batch"""} lowerCAmelCase = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: lowerCAmelCase = {0: """batch""", 1: """decoder_sequence"""} lowerCAmelCase = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase , direction="""inputs""" ) return common_inputs @property def __lowercase ( self : Optional[Any] ): return 13
529
"""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__)
529
1
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=13 , SCREAMING_SNAKE_CASE__ : Any=7 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : List[Any]=99 , SCREAMING_SNAKE_CASE__ : Optional[Any]=32 , SCREAMING_SNAKE_CASE__ : Dict=5 , SCREAMING_SNAKE_CASE__ : int=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=16 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[str]=0.0_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[int]="None" , SCREAMING_SNAKE_CASE__ : Any=3 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : str=None , ) -> Optional[int]: A : Union[str, Any] =parent A : List[str] =batch_size A : Tuple =seq_length A : Optional[int] =is_training A : Optional[Any] =use_input_mask A : Dict =use_token_type_ids A : int =use_labels A : Dict =vocab_size A : Any =hidden_size A : int =num_hidden_layers A : Any =num_attention_heads A : Any =intermediate_size A : Tuple =hidden_act A : Tuple =hidden_dropout_prob A : Optional[Any] =attention_probs_dropout_prob A : Optional[int] =max_position_embeddings A : Dict =type_vocab_size A : Any =type_sequence_label_size A : str =initializer_range A : List[str] =num_labels A : Dict =num_choices A : Optional[Any] =relative_attention A : Union[str, Any] =position_biased_input A : Tuple =pos_att_type A : Any =scope def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[Any]: A : Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : List[str] =None if self.use_input_mask: A : List[Any] =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) A : List[Any] =None if self.use_token_type_ids: A : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A : Union[str, Any] =None A : str =None A : List[str] =None if self.use_labels: A : Optional[int] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : Dict =ids_tensor([self.batch_size] , self.num_choices ) A : List[str] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[Any]: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: A : Optional[Any] =DebertaVaModel(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A : Tuple =model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ )[0] A : List[str] =model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ )[0] A : Union[str, Any] =model(lowerCAmelCase_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> str: A : Tuple =DebertaVaForMaskedLM(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A : Optional[Any] =model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Tuple: A : List[Any] =self.num_labels A : Any =DebertaVaForSequenceClassification(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A : Optional[int] =model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: A : str =self.num_labels A : Optional[Any] =DebertaVaForTokenClassification(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A : Tuple =model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: A : List[str] =DebertaVaForQuestionAnswering(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A : Dict =model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , start_positions=lowerCAmelCase_ , end_positions=lowerCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int ) -> str: A : List[Any] =DebertaVaForMultipleChoice(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A : Optional[int] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Optional[int] =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : str =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : List[str] =model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Optional[Any]: A : Tuple =self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) : List[Any] =config_and_inputs A : str ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): '''simple docstring''' lowercase : int = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( { '''feature-extraction''': DebertaVaModel, '''fill-mask''': DebertaVaForMaskedLM, '''question-answering''': DebertaVaForQuestionAnswering, '''text-classification''': DebertaVaForSequenceClassification, '''token-classification''': DebertaVaForTokenClassification, '''zero-shot''': DebertaVaForSequenceClassification, } if is_torch_available() else {} ) lowercase : Optional[Any] = True lowercase : Optional[Any] = False lowercase : Union[str, Any] = False lowercase : List[str] = False lowercase : Optional[Any] = False def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Dict: A : int =DebertaVaModelTester(self ) A : Optional[int] =ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : int ) -> str: A : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: A : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: A : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: A : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: A : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*lowerCAmelCase_ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : Optional[int] =DebertaVaModel.from_pretrained(lowerCAmelCase_ ) self.assertIsNotNone(lowerCAmelCase_ ) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason='Model not available yet' ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: pass @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : int =DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) A : Optional[Any] =torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] ) A : Any =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): A : Union[str, Any] =model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ )[0] # compare the actual values for a slice. A : List[str] =torch.tensor( [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCAmelCase_ , atol=1e-4 ) , f'{output[:, 1:4, 1:4]}' )
305
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class a ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase :List[Any] = IFPipeline lowerCamelCase :Optional[Any] = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} lowerCamelCase :str = TEXT_TO_IMAGE_BATCH_PARAMS lowerCamelCase :Optional[int] = PipelineTesterMixin.required_optional_params - {'''latents'''} def UpperCAmelCase ( self ) -> List[Any]: return self._get_dummy_components() def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=0 ) -> str: if str(lowerCAmelCase_ ).startswith("""mps""" ): _A = torch.manual_seed(lowerCAmelCase_ ) else: _A = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _A = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCAmelCase ( self ) -> Union[str, Any]: self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def UpperCAmelCase ( self ) -> int: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def UpperCAmelCase ( self ) -> List[str]: self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def UpperCAmelCase ( self ) -> Tuple: self._test_save_load_local() def UpperCAmelCase ( self ) -> Any: self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCAmelCase ( self ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class a ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase ( self ) -> Union[str, Any]: # if _A = IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa ) _A = IFSuperResolutionPipeline.from_pretrained( """DeepFloyd/IF-II-L-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("""cuda""" ) _A , _A = pipe_a.encode_prompt("""anime turtle""" , device="""cuda""" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() _A = None _A = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img _A = IFImgaImgPipeline(**pipe_a.components ) _A = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting _A = IFInpaintingPipeline(**pipe_a.components ) _A = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> str: # pipeline 1 _start_torch_memory_measurement() _A = torch.Generator(device="""cpu""" ).manual_seed(0 ) _A = pipe_a( prompt_embeds=lowerCAmelCase_ , negative_prompt_embeds=lowerCAmelCase_ , num_inference_steps=2 , generator=lowerCAmelCase_ , output_type="""np""" , ) _A = output.images[0] assert image.shape == (64, 64, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 _A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy""" ) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ ) # pipeline 2 _start_torch_memory_measurement() _A = torch.Generator(device="""cpu""" ).manual_seed(0 ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) _A = pipe_a( prompt_embeds=lowerCAmelCase_ , negative_prompt_embeds=lowerCAmelCase_ , image=lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=2 , output_type="""np""" , ) _A = output.images[0] assert image.shape == (2_56, 2_56, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: # pipeline 1 _start_torch_memory_measurement() _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) _A = torch.Generator(device="""cpu""" ).manual_seed(0 ) _A = pipe_a( prompt_embeds=lowerCAmelCase_ , negative_prompt_embeds=lowerCAmelCase_ , image=lowerCAmelCase_ , num_inference_steps=2 , generator=lowerCAmelCase_ , output_type="""np""" , ) _A = output.images[0] assert image.shape == (64, 64, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy""" ) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ ) # pipeline 2 _start_torch_memory_measurement() _A = torch.Generator(device="""cpu""" ).manual_seed(0 ) _A = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) _A = pipe_a( prompt_embeds=lowerCAmelCase_ , negative_prompt_embeds=lowerCAmelCase_ , image=lowerCAmelCase_ , original_image=lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=2 , output_type="""np""" , ) _A = output.images[0] assert image.shape == (2_56, 2_56, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[int]: # pipeline 1 _start_torch_memory_measurement() _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(lowerCAmelCase_ ) _A = torch.Generator(device="""cpu""" ).manual_seed(0 ) _A = pipe_a( prompt_embeds=lowerCAmelCase_ , negative_prompt_embeds=lowerCAmelCase_ , image=lowerCAmelCase_ , mask_image=lowerCAmelCase_ , num_inference_steps=2 , generator=lowerCAmelCase_ , output_type="""np""" , ) _A = output.images[0] assert image.shape == (64, 64, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy""" ) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ ) # pipeline 2 _start_torch_memory_measurement() _A = torch.Generator(device="""cpu""" ).manual_seed(0 ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) _A = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) _A = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(1 ) ).to(lowerCAmelCase_ ) _A = pipe_a( prompt_embeds=lowerCAmelCase_ , negative_prompt_embeds=lowerCAmelCase_ , image=lowerCAmelCase_ , mask_image=lowerCAmelCase_ , original_image=lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=2 , output_type="""np""" , ) _A = output.images[0] assert image.shape == (2_56, 2_56, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ ) def snake_case ( ) -> Tuple: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
401
0
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _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 SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _UpperCAmelCase : def __init__( self , a__ , a__=1_3 , a__=3_2 , a__=2 , a__=3 , a__=1_6 , a__=[1, 2, 1] , a__=[2, 2, 4] , a__=2 , a__=2.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=True , a__=0.0_2 , a__=1e-5 , a__=True , a__=None , a__=True , a__=1_0 , a__=8 , ): A__ = parent A__ = batch_size A__ = image_size A__ = patch_size A__ = num_channels A__ = embed_dim A__ = depths A__ = num_heads A__ = window_size A__ = mlp_ratio A__ = qkv_bias A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = drop_path_rate A__ = hidden_act A__ = use_absolute_embeddings A__ = patch_norm A__ = layer_norm_eps A__ = initializer_range A__ = is_training A__ = scope A__ = use_labels A__ = type_sequence_label_size A__ = encoder_stride def snake_case_ ( self): A__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size) A__ = self.get_config() return config, pixel_values, labels def snake_case_ ( self): return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def snake_case_ ( self , a__ , a__ , a__): A__ = SwinvaModel(config=snake_case__) model.to(snake_case__) model.eval() A__ = model(snake_case__) A__ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) A__ = int(config.embed_dim * 2 ** (len(config.depths) - 1)) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim)) def snake_case_ ( self , a__ , a__ , a__): A__ = SwinvaForMaskedImageModeling(config=snake_case__) model.to(snake_case__) model.eval() A__ = model(snake_case__) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images A__ = 1 A__ = SwinvaForMaskedImageModeling(snake_case__) model.to(snake_case__) model.eval() A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) A__ = model(snake_case__) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size)) def snake_case_ ( self , a__ , a__ , a__): A__ = self.type_sequence_label_size A__ = SwinvaForImageClassification(snake_case__) model.to(snake_case__) model.eval() A__ = model(snake_case__ , labels=snake_case__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def snake_case_ ( self): A__ = self.prepare_config_and_inputs() A__ , A__ , A__ = config_and_inputs A__ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class _UpperCAmelCase ( __a , __a , unittest.TestCase ): UpperCamelCase__ = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) UpperCamelCase__ = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def snake_case_ ( self): A__ = SwinvaModelTester(self) A__ = ConfigTester(self , config_class=snake_case__ , embed_dim=3_7) def snake_case_ ( self): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__) @unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.''') def snake_case_ ( self): pass @unittest.skip(reason='''Swinv2 does not use inputs_embeds''') def snake_case_ ( self): pass def snake_case_ ( self): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(snake_case__) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) A__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , nn.Linear)) def snake_case_ ( self): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(snake_case__) A__ = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ = [*signature.parameters.keys()] A__ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , snake_case__) def snake_case_ ( self): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = True for model_class in self.all_model_classes: A__ = True A__ = False A__ = True A__ = model_class(snake_case__) model.to(snake_case__) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(snake_case__ , snake_case__)) A__ = outputs.attentions A__ = len(self.model_tester.depths) self.assertEqual(len(snake_case__) , snake_case__) # check that output_attentions also work using config del inputs_dict["output_attentions"] A__ = True A__ = config.window_size**2 A__ = model_class(snake_case__) model.to(snake_case__) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(snake_case__ , snake_case__)) A__ = outputs.attentions self.assertEqual(len(snake_case__) , snake_case__) self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) A__ = len(snake_case__) # Check attention is always last and order is fine A__ = True A__ = True A__ = model_class(snake_case__) model.to(snake_case__) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(snake_case__ , snake_case__)) if hasattr(self.model_tester , '''num_hidden_states_types'''): A__ = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states A__ = 2 self.assertEqual(out_len + added_hidden_states , len(snake_case__)) A__ = outputs.attentions self.assertEqual(len(snake_case__) , snake_case__) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def snake_case_ ( self , a__ , a__ , a__ , a__): A__ = model_class(snake_case__) model.to(snake_case__) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(snake_case__ , snake_case__)) A__ = outputs.hidden_states A__ = getattr( self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths) + 1) self.assertEqual(len(snake_case__) , snake_case__) # Swinv2 has a different seq_length A__ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) A__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) A__ = outputs.reshaped_hidden_states self.assertEqual(len(snake_case__) , snake_case__) A__ , A__ , A__ , A__ = reshaped_hidden_states[0].shape A__ = ( reshaped_hidden_states[0].view(snake_case__ , snake_case__ , height * width).permute(0 , 2 , 1) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) def snake_case_ ( self): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: A__ = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , snake_case__) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , snake_case__) def snake_case_ ( self): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = 3 A__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) A__ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) A__ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) A__ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: A__ = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , (padded_height, padded_width)) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , (padded_height, padded_width)) def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*snake_case__) def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__) @slow def snake_case_ ( self): for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = SwinvaModel.from_pretrained(snake_case__) self.assertIsNotNone(snake_case__) def snake_case_ ( self): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = _config_zero_init(snake_case__) for model_class in self.all_model_classes: A__ = model_class(config=snake_case__) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) @require_vision @require_torch class _UpperCAmelCase ( unittest.TestCase ): @cached_property def snake_case_ ( self): return ( AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''') if is_vision_available() else None ) @slow def snake_case_ ( self): A__ = SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''').to( snake_case__) A__ = self.default_image_processor A__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''') A__ = image_processor(images=snake_case__ , return_tensors='''pt''').to(snake_case__) # forward pass with torch.no_grad(): A__ = model(**snake_case__) # verify the logits A__ = torch.Size((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , snake_case__) A__ = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6]).to(snake_case__) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case__ , atol=1e-4))
706
def lowerCAmelCase__ ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str )-> int: if height >= 1: move_tower(height - 1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) move_disk(UpperCamelCase_ , UpperCamelCase_ ) move_tower(height - 1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[Any] )-> str: print('''moving disk from''' , UpperCamelCase_ , '''to''' , UpperCamelCase_ ) def lowerCAmelCase__ ( )-> Tuple: A__ = int(input('''Height of hanoi: ''' ).strip() ) move_tower(UpperCamelCase_ , '''A''' , '''B''' , '''C''' ) if __name__ == "__main__": main()
526
0
def __lowercase( UpperCAmelCase__ = 1000 ): """simple docstring""" lowerCamelCase , lowerCamelCase = 1, 1 lowerCamelCase = 2 while True: lowerCamelCase = 0 lowerCamelCase = fa + fa lowerCamelCase , lowerCamelCase = fa, f index += 1 for _ in str(UpperCAmelCase__ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
623
from __future__ import annotations def __lowercase( UpperCAmelCase__ ): """simple docstring""" lowerCamelCase = 2 lowerCamelCase = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(UpperCAmelCase__ ) if n > 1: factors.append(UpperCAmelCase__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
623
1
import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger UpperCAmelCase__ : List[str] = get_logger(__name__) class __lowercase : def __init__( self , lowercase_ = None) -> List[Any]: __snake_case = ( os.path.join(lowercase_ , config.EXTRACTED_DATASETS_DIR) if cache_dir else config.EXTRACTED_DATASETS_PATH ) __snake_case = Extractor def _a ( self , lowercase_) -> str: from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" __snake_case = os.path.abspath(lowercase_) return os.path.join(self.extract_dir , hash_url_to_filename(lowercase_)) def _a ( self , lowercase_ , lowercase_) -> bool: return force_extract or ( not os.path.isfile(lowercase_) and not (os.path.isdir(lowercase_) and os.listdir(lowercase_)) ) def _a ( self , lowercase_ , lowercase_ = False) -> str: __snake_case = self.extractor.infer_extractor_format(lowercase_) if not extractor_format: return input_path __snake_case = self._get_output_path(lowercase_) if self._do_extract(lowercase_ , lowercase_): self.extractor.extract(lowercase_ , lowercase_ , lowercase_) return output_path class __lowercase ( lowerCamelCase__ ): @classmethod @abstractmethod def _a ( cls , lowercase_ , **lowercase_) -> bool: ... @staticmethod @abstractmethod def _a ( lowercase_ , lowercase_) -> None: ... class __lowercase ( lowerCamelCase__ , lowerCamelCase__ ): __UpperCAmelCase = [] @staticmethod def _a ( lowercase_ , lowercase_) -> Optional[Any]: with open(lowercase_ , 'rb') as f: return f.read(lowercase_) @classmethod def _a ( cls , lowercase_ , lowercase_ = b"") -> bool: if not magic_number: __snake_case = max(len(lowercase_) for cls_magic_number in cls.magic_numbers) try: __snake_case = cls.read_magic_number(lowercase_ , lowercase_) except OSError: return False return any(magic_number.startswith(lowercase_) for cls_magic_number in cls.magic_numbers) class __lowercase ( lowerCamelCase__ ): @classmethod def _a ( cls , lowercase_ , **lowercase_) -> bool: return tarfile.is_tarfile(lowercase_) @staticmethod def _a ( lowercase_ , lowercase_) -> Any: def resolved(lowercase_) -> str: return os.path.realpath(os.path.abspath(lowercase_)) def badpath(lowercase_ , lowercase_) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(lowercase_ , lowercase_)).startswith(lowercase_) def badlink(lowercase_ , lowercase_) -> bool: # Links are interpreted relative to the directory containing the link __snake_case = resolved(os.path.join(lowercase_ , os.path.dirname(info.name))) return badpath(info.linkname , base=lowercase_) __snake_case = resolved(lowercase_) for finfo in members: if badpath(finfo.name , lowercase_): logger.error(F"Extraction of {finfo.name} is blocked (illegal path)") elif finfo.issym() and badlink(lowercase_ , lowercase_): logger.error(F"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}") elif finfo.islnk() and badlink(lowercase_ , lowercase_): logger.error(F"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}") else: yield finfo @staticmethod def _a ( lowercase_ , lowercase_) -> None: os.makedirs(lowercase_ , exist_ok=lowercase_) __snake_case = tarfile.open(lowercase_) tar_file.extractall(lowercase_ , members=TarExtractor.safemembers(lowercase_ , lowercase_)) tar_file.close() class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [b'''\x1F\x8B'''] @staticmethod def _a ( lowercase_ , lowercase_) -> None: with gzip.open(lowercase_ , 'rb') as gzip_file: with open(lowercase_ , 'wb') as extracted_file: shutil.copyfileobj(lowercase_ , lowercase_) class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [ b'''PK\x03\x04''', b'''PK\x05\x06''', # empty archive b'''PK\x07\x08''', # spanned archive ] @classmethod def _a ( cls , lowercase_ , lowercase_ = b"") -> bool: if super().is_extractable(lowercase_ , magic_number=lowercase_): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(lowercase_ , 'rb') as fp: __snake_case = _EndRecData(lowercase_) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET]) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: __snake_case = fp.read(lowercase_) # CD is where we expect it to be if len(lowercase_) == sizeCentralDir: __snake_case = struct.unpack(lowercase_ , lowercase_) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def _a ( lowercase_ , lowercase_) -> None: os.makedirs(lowercase_ , exist_ok=lowercase_) with zipfile.ZipFile(lowercase_ , 'r') as zip_file: zip_file.extractall(lowercase_) zip_file.close() class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [b'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def _a ( lowercase_ , lowercase_) -> None: with lzma.open(lowercase_) as compressed_file: with open(lowercase_ , 'wb') as extracted_file: shutil.copyfileobj(lowercase_ , lowercase_) class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def _a ( lowercase_ , lowercase_) -> None: if not config.RARFILE_AVAILABLE: raise ImportError('Please pip install rarfile') import rarfile os.makedirs(lowercase_ , exist_ok=lowercase_) __snake_case = rarfile.RarFile(lowercase_) rf.extractall(lowercase_) rf.close() class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [b'''\x28\xb5\x2F\xFD'''] @staticmethod def _a ( lowercase_ , lowercase_) -> None: if not config.ZSTANDARD_AVAILABLE: raise ImportError('Please pip install zstandard') import zstandard as zstd __snake_case = zstd.ZstdDecompressor() with open(lowercase_ , 'rb') as ifh, open(lowercase_ , 'wb') as ofh: dctx.copy_stream(lowercase_ , lowercase_) class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [b'''\x42\x5A\x68'''] @staticmethod def _a ( lowercase_ , lowercase_) -> None: with bza.open(lowercase_ , 'rb') as compressed_file: with open(lowercase_ , 'wb') as extracted_file: shutil.copyfileobj(lowercase_ , lowercase_) class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [b'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def _a ( lowercase_ , lowercase_) -> None: if not config.PY7ZR_AVAILABLE: raise ImportError('Please pip install py7zr') import pyazr os.makedirs(lowercase_ , exist_ok=lowercase_) with pyazr.SevenZipFile(lowercase_ , 'r') as archive: archive.extractall(lowercase_) class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = [b'''\x04\x22\x4D\x18'''] @staticmethod def _a ( lowercase_ , lowercase_) -> None: if not config.LZ4_AVAILABLE: raise ImportError('Please pip install lz4') import lza.frame with lza.frame.open(lowercase_ , 'rb') as compressed_file: with open(lowercase_ , 'wb') as extracted_file: shutil.copyfileobj(lowercase_ , lowercase_) class __lowercase : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) __UpperCAmelCase = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def _a ( cls) -> int: return max( len(lowercase_) for extractor in cls.extractors.values() if issubclass(lowercase_ , lowercase_) for extractor_magic_number in extractor.magic_numbers) @staticmethod def _a ( lowercase_ , lowercase_) -> Tuple: try: return MagicNumberBaseExtractor.read_magic_number(lowercase_ , magic_number_length=lowercase_) except OSError: return b"" @classmethod def _a ( cls , lowercase_ , lowercase_ = False) -> bool: warnings.warn( 'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'infer_extractor_format\' instead.' , category=lowercase_ , ) __snake_case = cls.infer_extractor_format(lowercase_) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def _a ( cls , lowercase_) -> str: # <Added version="2.4.0"/> __snake_case = cls._get_magic_number_max_length() __snake_case = cls._read_magic_number(lowercase_ , lowercase_) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(lowercase_ , magic_number=lowercase_): return extractor_format @classmethod def _a ( cls , lowercase_ , lowercase_ , lowercase_ = None , lowercase_ = "deprecated" , ) -> None: os.makedirs(os.path.dirname(lowercase_) , exist_ok=lowercase_) # Prevent parallel extractions __snake_case = str(Path(lowercase_).with_suffix('.lock')) with FileLock(lowercase_): shutil.rmtree(lowercase_ , ignore_errors=lowercase_) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(lowercase_ , lowercase_): # passed as positional arg warnings.warn( 'Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'extractor_format\' instead.' , category=lowercase_ , ) __snake_case = extractor if extractor != 'deprecated' else extractor_format else: __snake_case = cls.extractors[extractor_format] return extractor.extract(lowercase_ , lowercase_) else: warnings.warn( 'Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an ' 'exception in 3.0.0.' , category=lowercase_ , ) for extractor in cls.extractors.values(): if extractor.is_extractable(lowercase_): return extractor.extract(lowercase_ , lowercase_)
676
import numpy as np def A ( snake_case__ : np.ndarray ) -> np.ndarray: '''simple docstring''' return 1 / (1 + np.exp(-vector )) def A ( snake_case__ : np.ndarray ) -> np.ndarray: '''simple docstring''' return vector * sigmoid(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod()
676
1
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger() def UpperCamelCase ( snake_case__ : int ,snake_case__ : str ,snake_case__ : LevitConfig ,snake_case__ : Path ,snake_case__ : bool = True ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": __snake_case :List[str] = timm.create_model("""levit_128s""" ,pretrained=__snake_case ) else: __snake_case :Any = timm.create_model("""levit_128""" ,pretrained=__snake_case ) if hidden_sizes == 192: __snake_case :str = timm.create_model("""levit_192""" ,pretrained=__snake_case ) if hidden_sizes == 256: __snake_case :Tuple = timm.create_model("""levit_256""" ,pretrained=__snake_case ) if hidden_sizes == 384: __snake_case :List[Any] = timm.create_model("""levit_384""" ,pretrained=__snake_case ) from_model.eval() __snake_case :List[Any] = LevitForImageClassificationWithTeacher(__snake_case ).eval() __snake_case :Union[str, Any] = OrderedDict() __snake_case :Union[str, Any] = from_model.state_dict() __snake_case :List[Any] = list(from_model.state_dict().keys() ) __snake_case :Any = list(our_model.state_dict().keys() ) print(len(__snake_case ) ,len(__snake_case ) ) for i in range(len(__snake_case ) ): __snake_case :Optional[int] = weights[og_keys[i]] our_model.load_state_dict(__snake_case ) __snake_case :Dict = torch.randn((2, 3, 224, 224) ) __snake_case :Optional[int] = from_model(__snake_case ) __snake_case :Optional[int] = our_model(__snake_case ).logits assert torch.allclose(__snake_case ,__snake_case ), "The model logits don't match the original one." __snake_case :str = name print(__snake_case ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __snake_case :Optional[int] = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(f'''Pushed {checkpoint_name}''' ) def UpperCamelCase ( snake_case__ : Path ,snake_case__ : str = None ,snake_case__ : bool = True ): '''simple docstring''' __snake_case :str = """imagenet-1k-id2label.json""" __snake_case :Optional[Any] = 1000 __snake_case :Any = (1, num_labels) __snake_case :int = """huggingface/label-files""" __snake_case :Union[str, Any] = num_labels __snake_case :int = json.load(open(hf_hub_download(__snake_case ,__snake_case ,repo_type="""dataset""" ) ,"""r""" ) ) __snake_case :List[str] = {int(__snake_case ): v for k, v in idalabel.items()} __snake_case :str = idalabel __snake_case :Optional[int] = {v: k for k, v in idalabel.items()} __snake_case :int = partial(__snake_case ,num_labels=__snake_case ,idalabel=__snake_case ,labelaid=__snake_case ) __snake_case :Optional[Any] = { """levit-128S""": 128, """levit-128""": 128, """levit-192""": 192, """levit-256""": 256, """levit-384""": 384, } __snake_case :Optional[Any] = { """levit-128S""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 6, 8] ,depths=[2, 3, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), """levit-128""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 8, 12] ,depths=[4, 4, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), """levit-192""": ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] ,num_attention_heads=[3, 5, 6] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), """levit-256""": ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] ,num_attention_heads=[4, 6, 8] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), """levit-384""": ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] ,num_attention_heads=[6, 9, 12] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0.1 ,), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] ,__snake_case ,names_to_config[model_name] ,__snake_case ,__snake_case ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) return config, expected_shape if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help="""The name of the model you wish to convert, it must be one of the supported Levit* architecture,""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""levit-dump-folder/""", type=Path, required=False, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) lowerCamelCase__ = parser.parse_args() lowerCamelCase__ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
455
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
0
def snake_case__ ( lowerCamelCase_=28123 ): A : Union[str, Any] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i A : str = set() A : Any = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(lowerCamelCase_ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
423
def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ ): return x if y == 0 else greatest_common_divisor(lowerCamelCase_ , x % y ) def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ ): return (x * y) // greatest_common_divisor(lowerCamelCase_ , lowerCamelCase_ ) def snake_case__ ( lowerCamelCase_ = 20 ): A : Optional[Any] = 1 for i in range(1 , n + 1 ): A : Dict = lcm(lowerCamelCase_ , lowerCamelCase_ ) return g if __name__ == "__main__": print(F"{solution() = }")
423
1
def _SCREAMING_SNAKE_CASE ( lowercase : int = 10 ): '''simple docstring''' if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError('Invalid input' ) lowerCamelCase_ = 10**n lowerCamelCase_ = 2_84_33 * (pow(2 , 7_83_04_57 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
70
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def _SCREAMING_SNAKE_CASE ( lowercase : str , lowercase : float | Decimal , lowercase : float = 10**-10 ): '''simple docstring''' lowerCamelCase_ = a while True: lowerCamelCase_ = Decimal(lowercase ) - ( Decimal(eval(lowercase ) ) / Decimal(eval(str(diff(lowercase ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(lowercase ) ) < precision: # noqa: S307 return float(lowercase ) # 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)}""")
70
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCamelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class _lowerCamelCase : """simple docstring""" snake_case = field( default="cifar10" , metadata={"help": "Name of a dataset from the datasets package"} ) snake_case = field( default=UpperCamelCase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) snake_case = field( default=UpperCamelCase , metadata={"help": "The column name of the images in the files."} ) snake_case = field(default=UpperCamelCase , metadata={"help": "A folder containing the training data."} ) snake_case = field(default=UpperCamelCase , metadata={"help": "A folder containing the validation data."} ) snake_case = field( default=0.1_5 , metadata={"help": "Percent to split off of train for validation."} ) snake_case = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def _snake_case ( self )->Union[str, Any]: '''simple docstring''' A_ : Union[str, Any] = {} if self.train_dir is not None: A_ : Tuple = self.train_dir if self.validation_dir is not None: A_ : Any = self.validation_dir A_ : Any = data_files if data_files else None @dataclass class _lowerCamelCase : """simple docstring""" snake_case = field( default=UpperCamelCase , metadata={ "help": ( "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch." ) } , ) snake_case = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name_or_path"} ) snake_case = field( default=UpperCamelCase , metadata={ "help": ( "Override some existing default config settings when a model is trained from scratch. Example: " "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" ) } , ) snake_case = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} ) snake_case = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case = field(default=UpperCamelCase , metadata={"help": "Name or path of preprocessor config."} ) snake_case = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) snake_case = field( default=0.7_5 , metadata={"help": "The ratio of the number of masked tokens in the input sequence."} ) snake_case = field( default=UpperCamelCase , metadata={"help": "Whether or not to train with normalized pixel values as target."} ) @dataclass class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" snake_case = field( default=1e-3 , metadata={"help": "Base learning rate: absolute_lr = base_lr * total_batch_size / 256."} ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): A_ : Optional[int] = torch.stack([example['''pixel_values'''] for example in examples] ) return {"pixel_values": pixel_values} def _SCREAMING_SNAKE_CASE ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. A_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. A_ , A_ , A_ : Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A_ , A_ , A_ : str = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_mae''' , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() A_ : int = training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE ) transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. A_ : Optional[int] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A_ : List[str] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset. A_ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. A_ : Union[str, Any] = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , SCREAMING_SNAKE_CASE ) and data_args.train_val_split > 0.0: A_ : Dict = ds['''train'''].train_test_split(data_args.train_val_split ) A_ : Tuple = split['''train'''] A_ : Tuple = split['''test'''] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. A_ : Optional[Any] = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: A_ : Any = ViTMAEConfig.from_pretrained(model_args.config_name , **SCREAMING_SNAKE_CASE ) elif model_args.model_name_or_path: A_ : Optional[int] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE ) else: A_ : List[str] = ViTMAEConfig() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(f'''New config: {config}''' ) # adapt config config.update( { '''mask_ratio''': model_args.mask_ratio, '''norm_pix_loss''': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: A_ : int = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **SCREAMING_SNAKE_CASE ) elif model_args.model_name_or_path: A_ : str = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE ) else: A_ : int = ViTImageProcessor() # create model if model_args.model_name_or_path: A_ : Optional[int] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) A_ : int = ViTMAEForPreTraining(SCREAMING_SNAKE_CASE ) if training_args.do_train: A_ : Optional[int] = ds['''train'''].column_names else: A_ : List[Any] = ds['''validation'''].column_names if data_args.image_column_name is not None: A_ : Optional[int] = data_args.image_column_name elif "image" in column_names: A_ : str = '''image''' elif "img" in column_names: A_ : str = '''img''' else: A_ : Optional[Any] = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: A_ : int = image_processor.size['''shortest_edge'''] else: A_ : int = (image_processor.size['''height'''], image_processor.size['''width''']) A_ : Union[str, Any] = Compose( [ Lambda(lambda SCREAMING_SNAKE_CASE : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(SCREAMING_SNAKE_CASE , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(SCREAMING_SNAKE_CASE ): A_ : Union[str, Any] = [transforms(SCREAMING_SNAKE_CASE ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: A_ : Optional[Any] = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(SCREAMING_SNAKE_CASE ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: A_ : int = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(SCREAMING_SNAKE_CASE ) # Compute absolute learning rate A_ : Union[str, Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: A_ : Union[str, Any] = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer A_ : int = Trainer( model=SCREAMING_SNAKE_CASE , args=SCREAMING_SNAKE_CASE , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=SCREAMING_SNAKE_CASE , data_collator=SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: A_ : int = None if training_args.resume_from_checkpoint is not None: A_ : Tuple = training_args.resume_from_checkpoint elif last_checkpoint is not None: A_ : Union[str, Any] = last_checkpoint A_ : Dict = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: A_ : List[Any] = trainer.evaluate() trainer.log_metrics('''eval''' , SCREAMING_SNAKE_CASE ) trainer.save_metrics('''eval''' , SCREAMING_SNAKE_CASE ) # Write model card and (optionally) push to hub A_ : Dict = { '''tasks''': '''masked-auto-encoding''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-auto-encoding'''], } if training_args.push_to_hub: trainer.push_to_hub(**SCREAMING_SNAKE_CASE ) else: trainer.create_model_card(**SCREAMING_SNAKE_CASE ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
152
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES UpperCamelCase = """tiny-wmt19-en-ru""" # Build # borrowed from a test UpperCamelCase = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] UpperCamelCase = dict(zip(vocab, range(len(vocab)))) UpperCamelCase = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = Path(tmpdirname) UpperCamelCase = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] UpperCamelCase = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] UpperCamelCase = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) UpperCamelCase = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) UpperCamelCase = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1000, tgt_vocab_size=1000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) UpperCamelCase = FSMTForConditionalGeneration(config) print(F'''num of params {tiny_model.num_parameters()}''') # Test UpperCamelCase = tokenizer(["""Making tiny model"""], return_tensors="""pt""") UpperCamelCase = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F'''Generated {mname_tiny}''') # Upload # transformers-cli upload tiny-wmt19-en-ru
152
1
A_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def UpperCAmelCase ( )-> None: '''simple docstring''' SCREAMING_SNAKE_CASE_ = input('''Enter message: ''' ) SCREAMING_SNAKE_CASE_ = input('''Enter key [alphanumeric]: ''' ) SCREAMING_SNAKE_CASE_ = input('''Encrypt/Decrypt [e/d]: ''' ) if mode.lower().startswith('''e''' ): SCREAMING_SNAKE_CASE_ = '''encrypt''' SCREAMING_SNAKE_CASE_ = encrypt_message(UpperCAmelCase ,UpperCAmelCase ) elif mode.lower().startswith('''d''' ): SCREAMING_SNAKE_CASE_ = '''decrypt''' SCREAMING_SNAKE_CASE_ = decrypt_message(UpperCAmelCase ,UpperCAmelCase ) print(f'''\n{mode.title()}ed message:''' ) print(UpperCAmelCase ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase )-> str: '''simple docstring''' return translate_message(UpperCAmelCase ,UpperCAmelCase ,'''encrypt''' ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase )-> str: '''simple docstring''' return translate_message(UpperCAmelCase ,UpperCAmelCase ,'''decrypt''' ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase )-> str: '''simple docstring''' SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = key.upper() for symbol in message: SCREAMING_SNAKE_CASE_ = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(UpperCAmelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(UpperCAmelCase ): SCREAMING_SNAKE_CASE_ = 0 else: translated.append(UpperCAmelCase ) return "".join(UpperCAmelCase ) if __name__ == "__main__": main()
393
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(">=", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType A_ = get_logger(__name__) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase=0 )-> List[str]: '''simple docstring''' os.makedirs(UpperCAmelCase ,exist_ok=UpperCAmelCase ) with FSDP.state_dict_type( UpperCAmelCase ,fsdp_plugin.state_dict_type ,fsdp_plugin.state_dict_config ,fsdp_plugin.optim_state_dict_config ): SCREAMING_SNAKE_CASE_ = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: SCREAMING_SNAKE_CASE_ = f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin''' SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,UpperCAmelCase ) if accelerator.process_index == 0: logger.info(f'''Saving model to {output_model_file}''' ) torch.save(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: SCREAMING_SNAKE_CASE_ = ( f'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Saving model to {output_model_file}''' ) torch.save(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,f'''{MODEL_NAME}_{model_index}''' ) os.makedirs(UpperCAmelCase ,exist_ok=UpperCAmelCase ) logger.info(f'''Saving model to {ckpt_dir}''' ) SCREAMING_SNAKE_CASE_ = {'''model''': state_dict} dist_cp.save_state_dict( state_dict=UpperCAmelCase ,storage_writer=dist_cp.FileSystemWriter(UpperCAmelCase ) ,planner=DefaultSavePlanner() ,) logger.info(f'''Model saved to {ckpt_dir}''' ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase=0 )-> List[str]: '''simple docstring''' accelerator.wait_for_everyone() with FSDP.state_dict_type( UpperCAmelCase ,fsdp_plugin.state_dict_type ,fsdp_plugin.state_dict_config ,fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(UpperCAmelCase ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( '''Set the `sync_module_states` flag to `True` so that model states are synced across processes when ''' '''initializing FSDP object''' ) return SCREAMING_SNAKE_CASE_ = f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin''' SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Loading model from {input_model_file}''' ) SCREAMING_SNAKE_CASE_ = torch.load(UpperCAmelCase ) logger.info(f'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: SCREAMING_SNAKE_CASE_ = ( f'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Loading model from {input_model_file}''' ) SCREAMING_SNAKE_CASE_ = torch.load(UpperCAmelCase ) logger.info(f'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: SCREAMING_SNAKE_CASE_ = ( os.path.join(UpperCAmelCase ,f'''{MODEL_NAME}_{model_index}''' ) if f'''{MODEL_NAME}''' not in input_dir else input_dir ) logger.info(f'''Loading model from {ckpt_dir}''' ) SCREAMING_SNAKE_CASE_ = {'''model''': model.state_dict()} dist_cp.load_state_dict( state_dict=UpperCAmelCase ,storage_reader=dist_cp.FileSystemReader(UpperCAmelCase ) ,planner=DefaultLoadPlanner() ,) SCREAMING_SNAKE_CASE_ = state_dict['''model'''] logger.info(f'''Model loaded from {ckpt_dir}''' ) model.load_state_dict(UpperCAmelCase ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase=0 )-> int: '''simple docstring''' os.makedirs(UpperCAmelCase ,exist_ok=UpperCAmelCase ) with FSDP.state_dict_type( UpperCAmelCase ,fsdp_plugin.state_dict_type ,fsdp_plugin.state_dict_config ,fsdp_plugin.optim_state_dict_config ): SCREAMING_SNAKE_CASE_ = FSDP.optim_state_dict(UpperCAmelCase ,UpperCAmelCase ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: SCREAMING_SNAKE_CASE_ = ( f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Saving Optimizer state to {output_optimizer_file}''' ) torch.save(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Optimizer state saved in {output_optimizer_file}''' ) else: SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,f'''{OPTIMIZER_NAME}_{optimizer_index}''' ) os.makedirs(UpperCAmelCase ,exist_ok=UpperCAmelCase ) logger.info(f'''Saving Optimizer state to {ckpt_dir}''' ) dist_cp.save_state_dict( state_dict={'''optimizer''': optim_state} ,storage_writer=dist_cp.FileSystemWriter(UpperCAmelCase ) ,planner=DefaultSavePlanner() ,) logger.info(f'''Optimizer state saved in {ckpt_dir}''' ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase=0 )-> Any: '''simple docstring''' accelerator.wait_for_everyone() with FSDP.state_dict_type( UpperCAmelCase ,fsdp_plugin.state_dict_type ,fsdp_plugin.state_dict_config ,fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: SCREAMING_SNAKE_CASE_ = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: SCREAMING_SNAKE_CASE_ = ( f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase ,UpperCAmelCase ) logger.info(f'''Loading Optimizer state from {input_optimizer_file}''' ) SCREAMING_SNAKE_CASE_ = torch.load(UpperCAmelCase ) logger.info(f'''Optimizer state loaded from {input_optimizer_file}''' ) else: SCREAMING_SNAKE_CASE_ = ( os.path.join(UpperCAmelCase ,f'''{OPTIMIZER_NAME}_{optimizer_index}''' ) if f'''{OPTIMIZER_NAME}''' not in input_dir else input_dir ) logger.info(f'''Loading Optimizer from {ckpt_dir}''' ) SCREAMING_SNAKE_CASE_ = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() ,optimizer_key='''optimizer''' ,storage_reader=dist_cp.FileSystemReader(UpperCAmelCase ) ,) SCREAMING_SNAKE_CASE_ = optim_state['''optimizer'''] logger.info(f'''Optimizer loaded from {ckpt_dir}''' ) SCREAMING_SNAKE_CASE_ = FSDP.optim_state_dict_to_load(UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ) optimizer.load_state_dict(UpperCAmelCase )
393
1
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class __snake_case ( pl.LightningModule ): def __init__( self : Any , _snake_case : Any): """simple docstring""" super().__init__() UpperCAmelCase_ = model UpperCAmelCase_ = 2 UpperCAmelCase_ = nn.Linear(self.model.config.hidden_size , self.num_labels) def lowerCamelCase ( self : Tuple): """simple docstring""" pass def A (__A : str , __A : str , __A : str ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ = LongformerModel.from_pretrained(__A ) UpperCAmelCase_ = LightningModel(__A ) UpperCAmelCase_ = torch.load(__A , map_location=torch.device('''cpu''' ) ) lightning_model.load_state_dict(ckpt['''state_dict'''] ) # init longformer question answering model UpperCAmelCase_ = LongformerForQuestionAnswering.from_pretrained(__A ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__A ) print(F"""Conversion successful. Model saved under {pytorch_dump_folder_path}""" ) if __name__ == "__main__": snake_case_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--longformer_model", default=None, type=str, required=True, help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.", ) parser.add_argument( "--longformer_question_answering_ckpt_path", default=None, type=str, required=True, help="Path the official PyTorch Lightning Checkpoint.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) snake_case_ : List[Any] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
169
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class __snake_case ( a , a ): @register_to_config def __init__( self : List[Any] , _snake_case : int = 128 , _snake_case : int = 256 , _snake_case : float = 2_0_0_0.0 , _snake_case : int = 768 , _snake_case : int = 12 , _snake_case : int = 12 , _snake_case : int = 64 , _snake_case : int = 2048 , _snake_case : float = 0.1 , ): """simple docstring""" super().__init__() UpperCAmelCase_ = nn.Sequential( nn.Linear(_snake_case , d_model * 4 , bias=_snake_case) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=_snake_case) , nn.SiLU() , ) UpperCAmelCase_ = nn.Embedding(_snake_case , _snake_case) UpperCAmelCase_ = False UpperCAmelCase_ = nn.Linear(_snake_case , _snake_case , bias=_snake_case) UpperCAmelCase_ = nn.Dropout(p=_snake_case) UpperCAmelCase_ = nn.ModuleList() for lyr_num in range(_snake_case): # FiLM conditional T5 decoder UpperCAmelCase_ = DecoderLayer(d_model=_snake_case , d_kv=_snake_case , num_heads=_snake_case , d_ff=_snake_case , dropout_rate=_snake_case) self.decoders.append(_snake_case) UpperCAmelCase_ = TaLayerNorm(_snake_case) UpperCAmelCase_ = nn.Dropout(p=_snake_case) UpperCAmelCase_ = nn.Linear(_snake_case , _snake_case , bias=_snake_case) def lowerCamelCase ( self : Optional[int] , _snake_case : str , _snake_case : List[str]): """simple docstring""" UpperCAmelCase_ = torch.mul(query_input.unsqueeze(-1) , key_input.unsqueeze(-2)) return mask.unsqueeze(-3) def lowerCamelCase ( self : Dict , _snake_case : Any , _snake_case : Optional[int] , _snake_case : int): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. UpperCAmelCase_ = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype) UpperCAmelCase_ = self.conditioning_emb(_snake_case).unsqueeze(1) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) UpperCAmelCase_ = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. UpperCAmelCase_ = torch.broadcast_to( torch.arange(_snake_case , device=decoder_input_tokens.device) , (batch, seq_length) , ) UpperCAmelCase_ = self.position_encoding(_snake_case) UpperCAmelCase_ = self.continuous_inputs_projection(_snake_case) inputs += position_encodings UpperCAmelCase_ = self.dropout(_snake_case) # decoder: No padding present. UpperCAmelCase_ = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype) # Translate encoding masks to encoder-decoder masks. UpperCAmelCase_ = [(x, self.encoder_decoder_mask(_snake_case , _snake_case)) for x, y in encodings_and_masks] # cross attend style: concat encodings UpperCAmelCase_ = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1) UpperCAmelCase_ = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1) for lyr in self.decoders: UpperCAmelCase_ = lyr( _snake_case , conditioning_emb=_snake_case , encoder_hidden_states=_snake_case , encoder_attention_mask=_snake_case , )[0] UpperCAmelCase_ = self.decoder_norm(_snake_case) UpperCAmelCase_ = self.post_dropout(_snake_case) UpperCAmelCase_ = self.spec_out(_snake_case) return spec_out class __snake_case ( nn.Module ): def __init__( self : Optional[Any] , _snake_case : Optional[Any] , _snake_case : Optional[Any] , _snake_case : List[Any] , _snake_case : Any , _snake_case : List[Any] , _snake_case : Optional[int]=1e-6): """simple docstring""" super().__init__() UpperCAmelCase_ = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=_snake_case , d_kv=_snake_case , num_heads=_snake_case , dropout_rate=_snake_case)) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=_snake_case , d_kv=_snake_case , num_heads=_snake_case , dropout_rate=_snake_case , layer_norm_epsilon=_snake_case , )) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=_snake_case , d_ff=_snake_case , dropout_rate=_snake_case , layer_norm_epsilon=_snake_case)) def lowerCamelCase ( self : Optional[Any] , _snake_case : str , _snake_case : Union[str, Any]=None , _snake_case : Any=None , _snake_case : Any=None , _snake_case : Any=None , _snake_case : Tuple=None , ): """simple docstring""" UpperCAmelCase_ = self.layer[0]( _snake_case , conditioning_emb=_snake_case , attention_mask=_snake_case , ) if encoder_hidden_states is not None: UpperCAmelCase_ = torch.where(encoder_attention_mask > 0 , 0 , -1e10).to( encoder_hidden_states.dtype) UpperCAmelCase_ = self.layer[1]( _snake_case , key_value_states=_snake_case , attention_mask=_snake_case , ) # Apply Film Conditional Feed Forward layer UpperCAmelCase_ = self.layer[-1](_snake_case , _snake_case) return (hidden_states,) class __snake_case ( nn.Module ): def __init__( self : List[Any] , _snake_case : int , _snake_case : str , _snake_case : int , _snake_case : str): """simple docstring""" super().__init__() UpperCAmelCase_ = TaLayerNorm(_snake_case) UpperCAmelCase_ = TaFiLMLayer(in_features=d_model * 4 , out_features=_snake_case) UpperCAmelCase_ = Attention(query_dim=_snake_case , heads=_snake_case , dim_head=_snake_case , out_bias=_snake_case , scale_qk=_snake_case) UpperCAmelCase_ = nn.Dropout(_snake_case) def lowerCamelCase ( self : str , _snake_case : str , _snake_case : Dict=None , _snake_case : List[str]=None , ): """simple docstring""" UpperCAmelCase_ = self.layer_norm(_snake_case) if conditioning_emb is not None: UpperCAmelCase_ = self.FiLMLayer(_snake_case , _snake_case) # Self-attention block UpperCAmelCase_ = self.attention(_snake_case) UpperCAmelCase_ = hidden_states + self.dropout(_snake_case) return hidden_states class __snake_case ( nn.Module ): def __init__( self : Any , _snake_case : Any , _snake_case : Any , _snake_case : Tuple , _snake_case : int , _snake_case : List[str]): """simple docstring""" super().__init__() UpperCAmelCase_ = Attention(query_dim=_snake_case , heads=_snake_case , dim_head=_snake_case , out_bias=_snake_case , scale_qk=_snake_case) UpperCAmelCase_ = TaLayerNorm(_snake_case , eps=_snake_case) UpperCAmelCase_ = nn.Dropout(_snake_case) def lowerCamelCase ( self : List[str] , _snake_case : Optional[Any] , _snake_case : List[str]=None , _snake_case : Tuple=None , ): """simple docstring""" UpperCAmelCase_ = self.layer_norm(_snake_case) UpperCAmelCase_ = self.attention( _snake_case , encoder_hidden_states=_snake_case , attention_mask=attention_mask.squeeze(1) , ) UpperCAmelCase_ = hidden_states + self.dropout(_snake_case) return layer_output class __snake_case ( nn.Module ): def __init__( self : List[Any] , _snake_case : Tuple , _snake_case : Any , _snake_case : List[Any] , _snake_case : Union[str, Any]): """simple docstring""" super().__init__() UpperCAmelCase_ = TaDenseGatedActDense(d_model=_snake_case , d_ff=_snake_case , dropout_rate=_snake_case) UpperCAmelCase_ = TaFiLMLayer(in_features=d_model * 4 , out_features=_snake_case) UpperCAmelCase_ = TaLayerNorm(_snake_case , eps=_snake_case) UpperCAmelCase_ = nn.Dropout(_snake_case) def lowerCamelCase ( self : Any , _snake_case : str , _snake_case : int=None): """simple docstring""" UpperCAmelCase_ = self.layer_norm(_snake_case) if conditioning_emb is not None: UpperCAmelCase_ = self.film(_snake_case , _snake_case) UpperCAmelCase_ = self.DenseReluDense(_snake_case) UpperCAmelCase_ = hidden_states + self.dropout(_snake_case) return hidden_states class __snake_case ( nn.Module ): def __init__( self : List[Any] , _snake_case : Union[str, Any] , _snake_case : Tuple , _snake_case : Union[str, Any]): """simple docstring""" super().__init__() UpperCAmelCase_ = nn.Linear(_snake_case , _snake_case , bias=_snake_case) UpperCAmelCase_ = nn.Linear(_snake_case , _snake_case , bias=_snake_case) UpperCAmelCase_ = nn.Linear(_snake_case , _snake_case , bias=_snake_case) UpperCAmelCase_ = nn.Dropout(_snake_case) UpperCAmelCase_ = NewGELUActivation() def lowerCamelCase ( self : List[str] , _snake_case : str): """simple docstring""" UpperCAmelCase_ = self.act(self.wi_a(_snake_case)) UpperCAmelCase_ = self.wi_a(_snake_case) UpperCAmelCase_ = hidden_gelu * hidden_linear UpperCAmelCase_ = self.dropout(_snake_case) UpperCAmelCase_ = self.wo(_snake_case) return hidden_states class __snake_case ( nn.Module ): def __init__( self : Any , _snake_case : Optional[Any] , _snake_case : List[Any]=1e-6): """simple docstring""" super().__init__() UpperCAmelCase_ = nn.Parameter(torch.ones(_snake_case)) UpperCAmelCase_ = eps def lowerCamelCase ( self : Tuple , _snake_case : List[str]): """simple docstring""" UpperCAmelCase_ = hidden_states.to(torch.floataa).pow(2).mean(-1 , keepdim=_snake_case) UpperCAmelCase_ = hidden_states * torch.rsqrt(variance + self.variance_epsilon) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: UpperCAmelCase_ = hidden_states.to(self.weight.dtype) return self.weight * hidden_states class __snake_case ( nn.Module ): def lowerCamelCase ( self : Tuple , _snake_case : torch.Tensor): """simple docstring""" return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.0_4_4_7_1_5 * torch.pow(_snake_case , 3.0)))) class __snake_case ( nn.Module ): def __init__( self : int , _snake_case : int , _snake_case : Optional[Any]): """simple docstring""" super().__init__() UpperCAmelCase_ = nn.Linear(_snake_case , out_features * 2 , bias=_snake_case) def lowerCamelCase ( self : Optional[Any] , _snake_case : Tuple , _snake_case : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = self.scale_bias(_snake_case) UpperCAmelCase_ , UpperCAmelCase_ = torch.chunk(_snake_case , 2 , -1) UpperCAmelCase_ = x * (1 + scale) + shift return x
169
1
def _lowerCAmelCase ( lowerCAmelCase_ :int = 600_851_475_143 )->int: '''simple docstring''' try: snake_case_ = int(lowerCAmelCase_ ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) snake_case_ = 1 snake_case_ = 2 while i * i <= n: while n % i == 0: snake_case_ = i n //= i i += 1 if n > 1: snake_case_ = n return int(lowerCAmelCase_ ) if __name__ == "__main__": print(F'''{solution() = }''')
283
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Dict = { '''vocab_file''': '''vocab.json''', '''tokenizer_config_file''': '''tokenizer_config.json''', '''merges_file''': '''merges.txt''', } SCREAMING_SNAKE_CASE :Optional[int] = { '''vocab_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json''' ), }, '''tokenizer_config_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json''' ), }, '''merges_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt''' ), }, } SCREAMING_SNAKE_CASE :List[str] = '''</w>''' SCREAMING_SNAKE_CASE :int = '''@@ ''' def _lowerCAmelCase ( lowerCAmelCase_ :int )->int: '''simple docstring''' snake_case_ = set() snake_case_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) snake_case_ = char return pairs # Speech2Text2 has no max input length SCREAMING_SNAKE_CASE :Tuple = {'''facebook/s2t-wav2vec2-large-en-de''': 10_24} class __lowerCAmelCase ( a ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = ['input_ids', 'attention_mask'] def __init__( self : List[Any] , _lowerCAmelCase : str , _lowerCAmelCase : Union[str, Any]="<s>" , _lowerCAmelCase : Tuple="<pad>" , _lowerCAmelCase : Union[str, Any]="</s>" , _lowerCAmelCase : str="<unk>" , _lowerCAmelCase : Union[str, Any]=False , _lowerCAmelCase : List[str]=None , **_lowerCAmelCase : List[str] , ) -> List[str]: """simple docstring""" super().__init__( unk_token=_lowerCAmelCase , bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , do_lower_case=_lowerCAmelCase , **_lowerCAmelCase , ) snake_case_ = do_lower_case with open(_lowerCAmelCase , encoding="utf-8" ) as vocab_handle: snake_case_ = json.load(_lowerCAmelCase ) snake_case_ = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F'''No merges files provided. {self.__class__.__name__} can only be used for decoding.''' ) snake_case_ = None snake_case_ = None else: with open(_lowerCAmelCase , encoding="utf-8" ) as merges_handle: snake_case_ = merges_handle.read().split("\n" )[:-1] snake_case_ = [tuple(merge.split()[:2] ) for merge in merges] snake_case_ = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) snake_case_ = {} @property def lowerCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return len(self.decoder ) def lowerCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def lowerCAmelCase__ ( self : Union[str, Any] , _lowerCAmelCase : Any ) -> Tuple: """simple docstring""" snake_case_ = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] snake_case_ = get_pairs(_lowerCAmelCase ) if not pairs: return token while True: snake_case_ = min(_lowerCAmelCase , key=lambda _lowerCAmelCase : self.bpe_ranks.get(_lowerCAmelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break snake_case_ , snake_case_ = bigram snake_case_ = [] snake_case_ = 0 while i < len(_lowerCAmelCase ): try: snake_case_ = word.index(_lowerCAmelCase , _lowerCAmelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) snake_case_ = j if word[i] == first and i < len(_lowerCAmelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 snake_case_ = tuple(_lowerCAmelCase ) snake_case_ = new_word if len(_lowerCAmelCase ) == 1: break else: snake_case_ = get_pairs(_lowerCAmelCase ) snake_case_ = " ".join(_lowerCAmelCase ) if word == "\n " + BPE_TOKEN_MERGES: snake_case_ = "\n" + BPE_TOKEN_MERGES if word.endswith(_lowerCAmelCase ): snake_case_ = word.replace(_lowerCAmelCase , "" ) snake_case_ = word.replace(" " , _lowerCAmelCase ) snake_case_ = word return word def lowerCAmelCase__ ( self : List[Any] , _lowerCAmelCase : List[str] ) -> List[Any]: """simple docstring""" if self.bpe_ranks is None: raise ValueError( "This tokenizer was instantiated without a `merges.txt` file, so" " that it can only be used for decoding, not for encoding." "Make sure to provide `merges.txt` file at instantiation to enable " "encoding." ) if self.do_lower_case: snake_case_ = text.lower() snake_case_ = text.split() snake_case_ = [] for token in text: if token: split_tokens.extend(list(self.bpe(_lowerCAmelCase ).split(" " ) ) ) return split_tokens def lowerCAmelCase__ ( self : str , _lowerCAmelCase : str ) -> int: """simple docstring""" return self.encoder.get(_lowerCAmelCase , self.encoder.get(self.unk_token ) ) def lowerCAmelCase__ ( self : int , _lowerCAmelCase : int ) -> str: """simple docstring""" snake_case_ = self.decoder.get(_lowerCAmelCase , self.unk_token ) return result def lowerCAmelCase__ ( self : Union[str, Any] , _lowerCAmelCase : List[str] ) -> str: """simple docstring""" snake_case_ = " ".join(_lowerCAmelCase ) # make sure @@ tokens are concatenated snake_case_ = "".join(string.split(_lowerCAmelCase ) ) return string def lowerCAmelCase__ ( self : Tuple , _lowerCAmelCase : str , _lowerCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_lowerCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return snake_case_ = os.path.join( _lowerCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) snake_case_ = os.path.join( _lowerCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_lowerCAmelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_lowerCAmelCase , ensure_ascii=_lowerCAmelCase ) + "\n" ) snake_case_ = 0 if self.bpe_ranks is None: return (vocab_file,) with open(_lowerCAmelCase , "w" , encoding="utf-8" ) as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _lowerCAmelCase : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.''' " Please check that the tokenizer is not corrupted!" ) snake_case_ = token_index writer.write(" ".join(_lowerCAmelCase ) + "\n" ) index += 1 return (vocab_file, merges_file)
283
1
def _UpperCamelCase ( lowercase__ , lowercase__ ): return "\n".join( F'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
710
from heapq import heappop, heappush import numpy as np def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = grid.shape __SCREAMING_SNAKE_CASE : Any = [-1, 1, 0, 0] __SCREAMING_SNAKE_CASE : Any = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = [(0, source)], set() __SCREAMING_SNAKE_CASE : Optional[Any] = np.full((rows, cols) , np.inf ) __SCREAMING_SNAKE_CASE : Tuple = 0 __SCREAMING_SNAKE_CASE : int = np.empty((rows, cols) , dtype=lowercase__ ) __SCREAMING_SNAKE_CASE : List[str] = None while queue: ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) : List[str] = heappop(lowercase__ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __SCREAMING_SNAKE_CASE : int = [] while (x, y) != source: path.append((x, y) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = predecessors[x, y] path.append(lowercase__ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(lowercase__ ) ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __SCREAMING_SNAKE_CASE : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(lowercase__ , (dist + 1, (nx, ny)) ) __SCREAMING_SNAKE_CASE : Optional[int] = dist + 1 __SCREAMING_SNAKE_CASE : Optional[Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
260
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( snake_case_ ): _snake_case : UNetaDModel _snake_case : ScoreSdeVeScheduler def __init__( self , lowerCamelCase , lowerCamelCase ): super().__init__() self.register_modules(unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self , lowerCamelCase = 1 , lowerCamelCase = 2000 , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , **lowerCamelCase , ): __a = self.unet.config.sample_size __a = (batch_size, 3, img_size, img_size) __a = self.unet __a = randn_tensor(lowerCamelCase , generator=lowerCamelCase ) * self.scheduler.init_noise_sigma __a = sample.to(self.device ) self.scheduler.set_timesteps(lowerCamelCase ) self.scheduler.set_sigmas(lowerCamelCase ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): __a = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): __a = self.unet(lowerCamelCase , lowerCamelCase ).sample __a = self.scheduler.step_correct(lowerCamelCase , lowerCamelCase , generator=lowerCamelCase ).prev_sample # prediction step __a = model(lowerCamelCase , lowerCamelCase ).sample __a = self.scheduler.step_pred(lowerCamelCase , lowerCamelCase , lowerCamelCase , generator=lowerCamelCase ) __a , __a = output.prev_sample, output.prev_sample_mean __a = sample_mean.clamp(0 , 1 ) __a = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (sample,) return ImagePipelineOutput(images=lowerCamelCase )
528
"""simple docstring""" import os def _lowerCamelCase( a = "matrix.txt" ): with open(os.path.join(os.path.dirname(a ) , a ) ) as in_file: __a = in_file.read() __a = [[int(a ) for cell in row.split("," )] for row in data.strip().splitlines()] __a = [[0 for cell in row] for row in grid] __a = len(grid[0] ) __a = [[0 for i in range(a )] for j in range(a )] __a = grid[0][0] for i in range(1 , a ): __a = grid[0][i] + dp[0][i - 1] for i in range(1 , a ): __a = grid[i][0] + dp[i - 1][0] for i in range(1 , a ): for j in range(1 , a ): __a = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(F'''{solution() = }''')
528
1
"""simple docstring""" def lowercase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' def count_of_possible_combinations(_SCREAMING_SNAKE_CASE : Optional[Any] ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(__A ) def lowercase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' def count_of_possible_combinations_with_dp_array( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] _UpperCAmelCase = sum( count_of_possible_combinations_with_dp_array(target - item , __A ) for item in array ) _UpperCAmelCase = answer return answer _UpperCAmelCase = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(__A , __A ) def lowercase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' _UpperCAmelCase = [0] * (target + 1) _UpperCAmelCase = 1 for i in range(1 , target + 1 ): for j in range(__A ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() __A : List[str] = 3 __A : Dict = 5 __A : Tuple = [1, 2, 5] print(combination_sum_iv(n, array, target))
701
"""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 _a ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase): """simple docstring""" UpperCamelCase__ = StableDiffusionXLImgaImgPipeline UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} UpperCamelCase__ = PipelineTesterMixin.required_optional_params - {"""latents"""} UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowercase__ ( self : Tuple )->int: torch.manual_seed(0 ) _UpperCAmelCase = 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 , ) _UpperCAmelCase = 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 ) _UpperCAmelCase = 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 ) _UpperCAmelCase = 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 , ) _UpperCAmelCase = CLIPTextModel(__UpperCamelCase ) _UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=__UpperCamelCase ) _UpperCAmelCase = CLIPTextModelWithProjection(__UpperCamelCase ) _UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=__UpperCamelCase ) _UpperCAmelCase = { '''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 lowercase__ ( self : int , __UpperCamelCase : Optional[int] , __UpperCamelCase : int=0 )->Any: _UpperCAmelCase = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase ) _UpperCAmelCase = image / 2 + 0.5 if str(__UpperCamelCase ).startswith('''mps''' ): _UpperCAmelCase = torch.manual_seed(__UpperCamelCase ) else: _UpperCAmelCase = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) _UpperCAmelCase = { '''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 lowercase__ ( self : Any )->int: _UpperCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = StableDiffusionXLImgaImgPipeline(**__UpperCamelCase ) _UpperCAmelCase = sd_pipe.to(__UpperCamelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCamelCase ) _UpperCAmelCase = self.get_dummy_inputs(__UpperCamelCase ) _UpperCAmelCase = sd_pipe(**__UpperCamelCase ).images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) _UpperCAmelCase = 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 lowercase__ ( self : Optional[Any] )->Optional[int]: super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def lowercase__ ( self : Optional[Any] )->List[Any]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def lowercase__ ( self : List[str] )->str: pass def lowercase__ ( self : Dict )->List[str]: _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = StableDiffusionXLImgaImgPipeline(**__UpperCamelCase ) _UpperCAmelCase = sd_pipe.to(__UpperCamelCase ) _UpperCAmelCase = sd_pipe.to(__UpperCamelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCamelCase ) # forward without prompt embeds _UpperCAmelCase = self.get_dummy_inputs(__UpperCamelCase ) _UpperCAmelCase = 3 * ['''this is a negative prompt'''] _UpperCAmelCase = negative_prompt _UpperCAmelCase = 3 * [inputs['''prompt''']] _UpperCAmelCase = sd_pipe(**__UpperCamelCase ) _UpperCAmelCase = output.images[0, -3:, -3:, -1] # forward with prompt embeds _UpperCAmelCase = self.get_dummy_inputs(__UpperCamelCase ) _UpperCAmelCase = 3 * ['''this is a negative prompt'''] _UpperCAmelCase = 3 * [inputs.pop('''prompt''' )] ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = sd_pipe.encode_prompt(__UpperCamelCase , negative_prompt=__UpperCamelCase ) _UpperCAmelCase = sd_pipe( **__UpperCamelCase , prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , pooled_prompt_embeds=__UpperCamelCase , negative_pooled_prompt_embeds=__UpperCamelCase , ) _UpperCAmelCase = 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 _a ( unittest.TestCase): """simple docstring""" def lowercase__ ( self : Union[str, Any] )->Any: super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self : Optional[Any] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Dict="cpu" , __UpperCamelCase : int=torch.floataa , __UpperCamelCase : Optional[Any]=0 )->Union[str, Any]: _UpperCAmelCase = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) _UpperCAmelCase = np.random.RandomState(__UpperCamelCase ).standard_normal((1, 4, 6_4, 6_4) ) _UpperCAmelCase = torch.from_numpy(__UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ) _UpperCAmelCase = { '''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 lowercase__ ( self : Optional[Any] )->Optional[Any]: _UpperCAmelCase = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) _UpperCAmelCase = self.get_inputs(__UpperCamelCase ) _UpperCAmelCase = pipe(**__UpperCamelCase ).images _UpperCAmelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) _UpperCAmelCase = 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
95
0
'''simple docstring''' def UpperCamelCase ( _lowerCamelCase : int = 50 ): A__ = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f"""{solution() = }""")
440
'''simple docstring''' from __future__ import annotations def UpperCamelCase ( _lowerCamelCase : list[int] ): # This function is recursive A__ = len(_lowerCamelCase ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else A__ = array[0] A__ = False A__ = 1 A__ = [] while not is_found and i < array_length: if array[i] < pivot: A__ = True A__ = [element for element in array[i:] if element >= array[i]] A__ = longest_subsequence(_lowerCamelCase ) if len(_lowerCamelCase ) > len(_lowerCamelCase ): A__ = temp_array else: i += 1 A__ = [element for element in array[1:] if element >= pivot] A__ = [pivot, *longest_subsequence(_lowerCamelCase )] if len(_lowerCamelCase ) > len(_lowerCamelCase ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
440
1
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class a ( __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase_ : Union[str, Any] = 'van' def __init__( self : str , lowerCamelCase__ : Union[str, Any]=224 , lowerCamelCase__ : Optional[int]=3 , lowerCamelCase__ : List[Any]=[7, 3, 3, 3] , lowerCamelCase__ : List[str]=[4, 2, 2, 2] , lowerCamelCase__ : Any=[64, 128, 320, 512] , lowerCamelCase__ : str=[3, 3, 12, 3] , lowerCamelCase__ : Optional[int]=[8, 8, 4, 4] , lowerCamelCase__ : Dict="gelu" , lowerCamelCase__ : Union[str, Any]=0.0_2 , lowerCamelCase__ : str=1e-6 , lowerCamelCase__ : Union[str, Any]=1e-2 , lowerCamelCase__ : str=0.0 , lowerCamelCase__ : List[Any]=0.0 , **lowerCamelCase__ : Any , ) -> int: """simple docstring""" super().__init__(**lowerCamelCase__ ) __lowercase = image_size __lowercase = num_channels __lowercase = patch_sizes __lowercase = strides __lowercase = hidden_sizes __lowercase = depths __lowercase = mlp_ratios __lowercase = hidden_act __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = layer_scale_init_value __lowercase = drop_path_rate __lowercase = dropout_rate
362
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class a ( __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase_ : UNetaDModel UpperCamelCase_ : KarrasVeScheduler def __init__( self : Tuple , lowerCamelCase__ : UNetaDModel , lowerCamelCase__ : KarrasVeScheduler ) -> Optional[Any]: """simple docstring""" super().__init__() self.register_modules(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ ) @torch.no_grad() def __call__( self : str , lowerCamelCase__ : int = 1 , lowerCamelCase__ : int = 50 , lowerCamelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase__ : Optional[str] = "pil" , lowerCamelCase__ : bool = True , **lowerCamelCase__ : int , ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" __lowercase = self.unet.config.sample_size __lowercase = (batch_size, 3, img_size, img_size) __lowercase = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) __lowercase = randn_tensor(lowerCamelCase__ , generator=lowerCamelCase__ , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(lowerCamelCase__ ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper __lowercase = self.scheduler.schedule[t] __lowercase = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat __lowercase , __lowercase = self.scheduler.add_noise_to_input(lowerCamelCase__ , lowerCamelCase__ , generator=lowerCamelCase__ ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. __lowercase = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev __lowercase = self.scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. __lowercase = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample __lowercase = self.scheduler.step_correct( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , step_output.prev_sample , step_output['''derivative'''] , ) __lowercase = step_output.prev_sample __lowercase = (sample / 2 + 0.5).clamp(0 , 1 ) __lowercase = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __lowercase = self.numpy_to_pil(lowerCamelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase__ )
362
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/resolve/main/config.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/config.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/config.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json""", } class __magic_name__ ( lowerCAmelCase ): """simple docstring""" lowerCamelCase__ = 'bloom' lowerCamelCase__ = ['past_key_values'] lowerCamelCase__ = { 'num_hidden_layers': 'n_layer', 'num_attention_heads': 'n_head', } def __init__( self , lowerCamelCase=25_0880 , lowerCamelCase=64 , lowerCamelCase=2 , lowerCamelCase=8 , lowerCamelCase=1E-5 , lowerCamelCase=0.02 , lowerCamelCase=True , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=False , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=1 , lowerCamelCase=False , **lowerCamelCase , ): '''simple docstring''' __A : List[str] = vocab_size # Backward compatibility with n_embed kwarg __A : List[Any] = kwargs.pop("n_embed" , lowerCamelCase ) __A : int = hidden_size if n_embed is None else n_embed __A : Optional[Any] = n_layer __A : Union[str, Any] = n_head __A : str = layer_norm_epsilon __A : Union[str, Any] = initializer_range __A : Union[str, Any] = use_cache __A : Dict = pretraining_tp __A : Optional[Any] = apply_residual_connection_post_layernorm __A : Optional[Any] = hidden_dropout __A : Union[str, Any] = attention_dropout __A : List[str] = bos_token_id __A : Tuple = eos_token_id __A : Any = slow_but_exact super().__init__(bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase ) class __magic_name__ ( lowerCAmelCase ): """simple docstring""" lowerCamelCase__ = version.parse('1.12' ) def __init__( self , lowerCamelCase , lowerCamelCase = "default" , lowerCamelCase = None , lowerCamelCase = False , ): '''simple docstring''' super().__init__(lowerCamelCase , task=lowerCamelCase , patching_specs=lowerCamelCase , use_past=lowerCamelCase ) if not getattr(self._config , "pad_token_id" , lowerCamelCase ): # TODO: how to do that better? __A : Dict = 0 @property def lowerCAmelCase__ ( self ): '''simple docstring''' __A : Optional[int] = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(lowerCamelCase , direction="inputs" , inverted_values_shape=lowerCamelCase ) __A : Any = {0: "batch", 1: "past_sequence + sequence"} else: __A : Tuple = {0: "batch", 1: "sequence"} return common_inputs @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self._config.n_layer @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self._config.n_head @property def lowerCAmelCase__ ( self ): '''simple docstring''' return 1E-3 def lowerCAmelCase__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): '''simple docstring''' __A : Union[str, Any] = super(lowerCamelCase , self ).generate_dummy_inputs( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) # We need to order the input in the way they appears in the forward() __A : Optional[Any] = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __A ,__A : List[str] = common_inputs["input_ids"].shape # Not using the same length for past_key_values __A : Optional[int] = seqlen + 2 __A : Optional[int] = self._config.hidden_size // self.num_attention_heads __A : Union[str, Any] = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) __A : List[str] = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) __A : Optional[Any] = [ (torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) for _ in range(self.num_layers ) ] __A : int = common_inputs["attention_mask"] if self.use_past: __A : Optional[int] = ordered_inputs["attention_mask"].dtype __A : Any = torch.cat( [ordered_inputs["attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase , dtype=lowerCamelCase )] , dim=1 ) return ordered_inputs @property def lowerCAmelCase__ ( self ): '''simple docstring''' return 13
111
'''simple docstring''' import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {name: getattr(transformers, name + """Fast""") for name in SLOW_TO_FAST_CONVERTERS} def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f"Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}." ) if tokenizer_name is None: __A : Tuple = TOKENIZER_CLASSES else: __A : Dict = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE , tokenizer_name + "Fast" )} logger.info(f"Loading tokenizer classes: {tokenizer_names}" ) for tokenizer_name in tokenizer_names: __A : int = TOKENIZER_CLASSES[tokenizer_name] __A : Union[str, Any] = True if checkpoint_name is None: __A : Dict = list(tokenizer_class.max_model_input_sizes.keys() ) else: __A : str = [checkpoint_name] logger.info(f"For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}" ) for checkpoint in checkpoint_names: logger.info(f"Loading {tokenizer_class.__class__.__name__} {checkpoint}" ) # Load tokenizer __A : List[str] = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , force_download=SCREAMING_SNAKE_CASE ) # Save fast tokenizer logger.info(f"Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}" ) # For organization names we create sub-directories if "/" in checkpoint: __A ,__A : Optional[Any] = checkpoint.split("/" ) __A : str = os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) elif add_prefix: __A : Optional[int] = checkpoint __A : Any = dump_path else: __A : int = None __A : Optional[int] = dump_path logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}" ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __A : Any = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __A : Optional[int] = file_path.split(SCREAMING_SNAKE_CASE )[-1][0] if next_char == "/": __A : Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __A : Union[str, Any] = None logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}" ) __A : Tuple = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE , legacy_format=SCREAMING_SNAKE_CASE , filename_prefix=SCREAMING_SNAKE_CASE ) logger.info(f"=> File names {file_names}" ) for file_name in file_names: if not file_name.endswith("tokenizer.json" ): os.remove(SCREAMING_SNAKE_CASE ) logger.info(f"=> removing {file_name}" ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output generated fast tokenizer files.""" ) parser.add_argument( """--tokenizer_name""", default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ """download and convert all the checkpoints from AWS.""" ), ) parser.add_argument( """--checkpoint_name""", default=None, type=str, help="""Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.""", ) parser.add_argument( """--force_download""", action="""store_true""", help="""Re-download checkpoints.""", ) _UpperCamelCase = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
111
1
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCAmelCase = random.Random() def __A ( lowerCamelCase_ , lowerCamelCase_=1.0 , lowerCamelCase_=None , lowerCamelCase_=None ): """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE : Optional[Any] = global_rng SCREAMING_SNAKE_CASE : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int]=7 , lowerCamelCase_ : Optional[int]=4_00 , lowerCamelCase_ : int=20_00 , lowerCamelCase_ : List[str]=20_48 , lowerCamelCase_ : Optional[Any]=1_28 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : Dict=30 , lowerCamelCase_ : Dict=4_41_00 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = min_seq_length SCREAMING_SNAKE_CASE : Any = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : int = spectrogram_length SCREAMING_SNAKE_CASE : List[Any] = feature_size SCREAMING_SNAKE_CASE : Any = num_audio_channels SCREAMING_SNAKE_CASE : Tuple = hop_length SCREAMING_SNAKE_CASE : str = chunk_length SCREAMING_SNAKE_CASE : Dict = sampling_rate def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : Any=False ): '''simple docstring''' def _flatten(lowerCamelCase_ : Dict ): return list(itertools.chain(*lowerCamelCase_ ) ) if equal_length: SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(lowerCamelCase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = TvltFeatureExtractor def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TvltFeatureExtractionTester(self ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase_ , """spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """sampling_rate""" ) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Any = feat_extract_first.save_pretrained(lowerCamelCase_ )[0] check_json_file_has_correct_format(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : List[Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : int = os.path.join(lowerCamelCase_ , """feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class.from_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : int = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : List[str] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Optional[Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] SCREAMING_SNAKE_CASE : int = [np.asarray(lowerCamelCase_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 , mask_audio=lowerCamelCase_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] SCREAMING_SNAKE_CASE : int = np.asarray(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Union[str, Any] = ds.sort("""id""" ).select(range(lowerCamelCase_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : Tuple = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(lowerCamelCase_ , return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_92, 1_28) ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , lowerCamelCase_ , atol=1e-4 ) )
79
'''simple docstring''' import math class UpperCamelCase__ : """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Tuple=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' SCREAMING_SNAKE_CASE : Any = n SCREAMING_SNAKE_CASE : Optional[int] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # adjacency matrix for weight SCREAMING_SNAKE_CASE : Union[str, Any] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # dp[i][j] stores minimum distance from i to j def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = w def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): SCREAMING_SNAKE_CASE : Union[str, Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": __UpperCAmelCase = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
79
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { """transfo-xl-wt103""": """https://huggingface.co/transfo-xl-wt103/resolve/main/config.json""", } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = """transfo-xl""" __magic_name__ :Any = ["""mems"""] __magic_name__ :List[str] = { """n_token""": """vocab_size""", """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , __UpperCAmelCase=2_6_7_7_3_5 , __UpperCAmelCase=[2_0_0_0_0, 4_0_0_0_0, 2_0_0_0_0_0] , __UpperCAmelCase=1_0_2_4 , __UpperCAmelCase=1_0_2_4 , __UpperCAmelCase=1_6 , __UpperCAmelCase=6_4 , __UpperCAmelCase=4_0_9_6 , __UpperCAmelCase=4 , __UpperCAmelCase=False , __UpperCAmelCase=1_8 , __UpperCAmelCase=1_6_0_0 , __UpperCAmelCase=1_0_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=0 , __UpperCAmelCase=-1 , __UpperCAmelCase=True , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.0 , __UpperCAmelCase=True , __UpperCAmelCase="normal" , __UpperCAmelCase=0.01 , __UpperCAmelCase=0.01 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=0 , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :List[str] = vocab_size lowerCAmelCase__ :Optional[int] = [] self.cutoffs.extend(__UpperCAmelCase ) if proj_share_all_but_first: lowerCAmelCase__ :int = [False] + [True] * len(self.cutoffs ) else: lowerCAmelCase__ :List[Any] = [False] + [False] * len(self.cutoffs ) lowerCAmelCase__ :Union[str, Any] = d_model lowerCAmelCase__ :str = d_embed lowerCAmelCase__ :str = d_head lowerCAmelCase__ :List[str] = d_inner lowerCAmelCase__ :List[str] = div_val lowerCAmelCase__ :Optional[int] = pre_lnorm lowerCAmelCase__ :Union[str, Any] = n_layer lowerCAmelCase__ :Optional[Any] = n_head lowerCAmelCase__ :Optional[int] = mem_len lowerCAmelCase__ :Optional[Any] = same_length lowerCAmelCase__ :Any = attn_type lowerCAmelCase__ :Union[str, Any] = clamp_len lowerCAmelCase__ :List[Any] = sample_softmax lowerCAmelCase__ :Any = adaptive lowerCAmelCase__ :Union[str, Any] = dropout lowerCAmelCase__ :Optional[Any] = dropatt lowerCAmelCase__ :str = untie_r lowerCAmelCase__ :Optional[int] = init lowerCAmelCase__ :str = init_range lowerCAmelCase__ :Union[str, Any] = proj_init_std lowerCAmelCase__ :List[str] = init_std lowerCAmelCase__ :int = layer_norm_epsilon super().__init__(eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) @property def snake_case ( self ): '''simple docstring''' logger.info(F"The model {self.model_type} is one of the few models that has no sequence length limit." ) return -1 @max_position_embeddings.setter def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' raise NotImplementedError( F"The model {self.model_type} is one of the few models that has no sequence length limit." )
93
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { """configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""], """processing_mgp_str""": ["""MgpstrProcessor"""], """tokenization_mgp_str""": ["""MgpstrTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""", """MgpstrModel""", """MgpstrPreTrainedModel""", """MgpstrForSceneTextRecognition""", ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
93
1
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class __UpperCAmelCase ( __lowerCAmelCase ): """simple docstring""" def snake_case_ ( self ): 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 snake_case_ ( self ): __a = {'''col_1''': [3, 2, 1, 0], '''col_2''': ['''a''', '''b''', '''c''', '''d''']} return Dataset.from_dict(lowerCamelCase__ ) def snake_case_ ( self ): __a = self._create_example_records() __a = Dataset.from_list(lowerCamelCase__ ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(lowerCamelCase__ ): self.assertDictEqual(lowerCamelCase__ , example_records[i] ) def snake_case_ ( self ): __a = self._create_example_records() __a = Dataset.from_list(lowerCamelCase__ ) __a = 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 snake_case_ ( self ): # checks what happens with missing columns __a = [{'''col_1''': 1}, {'''col_2''': '''x'''}] __a = Dataset.from_list(lowerCamelCase__ ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_ ( self ): # checks if the type can be inferred from the second record __a = [{'''col_1''': []}, {'''col_1''': [1, 2]}] __a = Dataset.from_list(lowerCamelCase__ ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_ ( self ): __a = Dataset.from_list([] ) self.assertEqual(len(lowerCamelCase__ ) , 0 ) self.assertListEqual(dset.column_names , [] )
718
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __UpperCAmelCase ( __A , unittest.TestCase ): """simple docstring""" _lowerCamelCase = LDMTextToImagePipeline _lowerCamelCase = TEXT_TO_IMAGE_PARAMS - { """negative_prompt""", """negative_prompt_embeds""", """cross_attention_kwargs""", """prompt_embeds""", } _lowerCamelCase = PipelineTesterMixin.required_optional_params - { """num_images_per_prompt""", """callback""", """callback_steps""", } _lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase = False def snake_case_ ( self ): torch.manual_seed(0 ) __a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) __a = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__A , set_alpha_to_one=__A , ) torch.manual_seed(0 ) __a = 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 , ) torch.manual_seed(0 ) __a = 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 , ) __a = CLIPTextModel(__A ) __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __a = { """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def snake_case_ ( self , __A , __A=0 ): if str(__A ).startswith("""mps""" ): __a = torch.manual_seed(__A ) else: __a = torch.Generator(device=__A ).manual_seed(__A ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def snake_case_ ( self ): __a = """cpu""" # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = LDMTextToImagePipeline(**__A ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) __a = self.get_dummy_inputs(__A ) __a = pipe(**__A ).images __a = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) __a = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case_ ( self , __A , __A=torch.floataa , __A=0 ): __a = torch.manual_seed(__A ) __a = np.random.RandomState(__A ).standard_normal((1, 4, 32, 32) ) __a = torch.from_numpy(__A ).to(device=__A , dtype=__A ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def snake_case_ ( self ): __a = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__A ) pipe.set_progress_bar_config(disable=__A ) __a = self.get_inputs(__A ) __a = pipe(**__A ).images __a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 256, 256, 3) __a = np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878] ) __a = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case_ ( self , __A , __A=torch.floataa , __A=0 ): __a = torch.manual_seed(__A ) __a = np.random.RandomState(__A ).standard_normal((1, 4, 32, 32) ) __a = torch.from_numpy(__A ).to(device=__A , dtype=__A ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def snake_case_ ( self ): __a = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__A ) pipe.set_progress_bar_config(disable=__A ) __a = self.get_inputs(__A ) __a = pipe(**__A ).images[0] __a = load_numpy( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""" ) __a = np.abs(expected_image - image ).max() assert max_diff < 1E-3
209
0
"""simple docstring""" def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ )-> int: """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( )-> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
554
"""simple docstring""" def lowerCamelCase__ ( UpperCAmelCase_ = 60_08_51_47_51_43 )-> int: """simple docstring""" try: UpperCamelCase = int(UpperCAmelCase_ ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) UpperCamelCase = 2 UpperCamelCase = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 UpperCamelCase = i while n % i == 0: UpperCamelCase = n // i i += 1 return int(UpperCAmelCase_ ) if __name__ == "__main__": print(F'''{solution() = }''')
554
1
'''simple docstring''' import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE = "▁" , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = "<unk>" , SCREAMING_SNAKE_CASE = "</s>" , SCREAMING_SNAKE_CASE = "<pad>" , ) -> Tuple: """simple docstring""" A : Optional[int] = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } A : Tuple = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): A : List[str] = token_dict['''token'''] A : int = Tokenizer(Unigram() ) A : Union[str, Any] = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''' ) , ''' ''' ), normalizers.Lowercase(), ] ) A : List[str] = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=SCREAMING_SNAKE_CASE , add_prefix_space=SCREAMING_SNAKE_CASE ), pre_tokenizers.Digits(individual_digits=SCREAMING_SNAKE_CASE ), pre_tokenizers.Punctuation(), ] ) A : List[Any] = decoders.Metaspace(replacement=SCREAMING_SNAKE_CASE , add_prefix_space=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = TemplateProcessing( single=F'$A {self.special_tokens["eos"]["token"]}' , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) A : str = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 8000 , SCREAMING_SNAKE_CASE = True , ) -> Union[str, Any]: """simple docstring""" A : List[Any] = trainers.UnigramTrainer( vocab_size=SCREAMING_SNAKE_CASE , special_tokens=self.special_tokens_list , show_progress=SCREAMING_SNAKE_CASE , ) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Optional[Any] = [files] self._tokenizer.train(SCREAMING_SNAKE_CASE , trainer=SCREAMING_SNAKE_CASE ) self.add_unk_id() def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 8000 , SCREAMING_SNAKE_CASE = True , ) -> Any: """simple docstring""" A : Union[str, Any] = trainers.UnigramTrainer( vocab_size=SCREAMING_SNAKE_CASE , special_tokens=self.special_tokens_list , show_progress=SCREAMING_SNAKE_CASE , ) self._tokenizer.train_from_iterator(SCREAMING_SNAKE_CASE , trainer=SCREAMING_SNAKE_CASE ) self.add_unk_id() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = json.loads(self._tokenizer.to_str() ) A : Tuple = self.special_tokens['''unk''']['''id'''] A : Any = Tokenizer.from_str(json.dumps(SCREAMING_SNAKE_CASE ) )
343
'''simple docstring''' import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = tempfile.mkdtemp() A : List[Any] = SamImageProcessor() A : Optional[int] = SamProcessor(SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ).image_processor def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] A : Tuple = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Any = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 ) A : int = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = self.get_image_processor() A : Tuple = SamProcessor(image_processor=SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.prepare_image_inputs() A : List[str] = image_processor(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : Any = processor(images=SCREAMING_SNAKE_CASE , return_tensors='''np''' ) input_feat_extract.pop('''original_sizes''' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('''reshaped_input_sizes''' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : str = self.get_image_processor() A : Union[str, Any] = SamProcessor(image_processor=SCREAMING_SNAKE_CASE ) A : str = [torch.ones((1, 3, 5, 5) )] A : Union[str, Any] = [[1764, 2646]] A : Tuple = [[683, 1024]] A : Tuple = processor.post_process_masks(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) A : Union[str, Any] = processor.post_process_masks( SCREAMING_SNAKE_CASE , torch.tensor(SCREAMING_SNAKE_CASE ) , torch.tensor(SCREAMING_SNAKE_CASE ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np A : Optional[Any] = [np.ones((1, 3, 5, 5) )] A : Tuple = processor.post_process_masks(SCREAMING_SNAKE_CASE , np.array(SCREAMING_SNAKE_CASE ) , np.array(SCREAMING_SNAKE_CASE ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) A : List[str] = [[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE ): A : Union[str, Any] = processor.post_process_masks(SCREAMING_SNAKE_CASE , np.array(SCREAMING_SNAKE_CASE ) , np.array(SCREAMING_SNAKE_CASE ) ) @require_vision @require_tf class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = tempfile.mkdtemp() A : Optional[int] = SamImageProcessor() A : List[Any] = SamProcessor(SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ).image_processor def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Union[str, Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] A : Any = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : List[str] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 ) A : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Any = self.get_image_processor() A : Union[str, Any] = SamProcessor(image_processor=SCREAMING_SNAKE_CASE ) A : Tuple = self.prepare_image_inputs() A : Any = image_processor(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : Union[str, Any] = processor(images=SCREAMING_SNAKE_CASE , return_tensors='''np''' ) input_feat_extract.pop('''original_sizes''' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('''reshaped_input_sizes''' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Any = self.get_image_processor() A : Optional[int] = SamProcessor(image_processor=SCREAMING_SNAKE_CASE ) A : List[Any] = [tf.ones((1, 3, 5, 5) )] A : Any = [[1764, 2646]] A : str = [[683, 1024]] A : List[Any] = processor.post_process_masks(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) A : List[Any] = processor.post_process_masks( SCREAMING_SNAKE_CASE , tf.convert_to_tensor(SCREAMING_SNAKE_CASE ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE ) , return_tensors='''tf''' , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np A : Dict = [np.ones((1, 3, 5, 5) )] A : List[str] = processor.post_process_masks( SCREAMING_SNAKE_CASE , np.array(SCREAMING_SNAKE_CASE ) , np.array(SCREAMING_SNAKE_CASE ) , return_tensors='''tf''' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) A : Union[str, Any] = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : Union[str, Any] = processor.post_process_masks( SCREAMING_SNAKE_CASE , np.array(SCREAMING_SNAKE_CASE ) , np.array(SCREAMING_SNAKE_CASE ) , return_tensors='''tf''' ) @require_vision @require_torchvision class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = tempfile.mkdtemp() A : Tuple = SamImageProcessor() A : Dict = SamProcessor(SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ).image_processor def __lowerCAmelCase ( self ) -> Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] A : Tuple = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Union[str, Any] = self.get_image_processor() A : int = SamProcessor(image_processor=SCREAMING_SNAKE_CASE ) A : Dict = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Tuple = [tf.convert_to_tensor(SCREAMING_SNAKE_CASE )] A : Optional[Any] = [torch.tensor(SCREAMING_SNAKE_CASE )] A : Dict = [[1764, 2646]] A : List[Any] = [[683, 1024]] A : List[Any] = processor.post_process_masks( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) A : Optional[Any] = processor.post_process_masks( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Optional[int] = self.get_image_processor() A : Union[str, Any] = SamProcessor(image_processor=SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.prepare_image_inputs() A : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors='''pt''' )['''pixel_values'''].numpy() A : str = processor(images=SCREAMING_SNAKE_CASE , return_tensors='''pt''' )['''pixel_values'''].numpy() A : List[str] = image_processor(SCREAMING_SNAKE_CASE , return_tensors='''tf''' )['''pixel_values'''].numpy() A : int = processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' )['''pixel_values'''].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) )
343
1
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import sys import transformers UpperCAmelCase__ = '''3''' print('''Python version:''', sys.version) print('''transformers version:''', transformers.__version__) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) print('''NCCL version:''', torch.cuda.nccl.version()) except ImportError: print('''Torch version:''', None) try: import deepspeed print('''DeepSpeed version:''', deepspeed.__version__) except ImportError: print('''DeepSpeed version:''', None) try: import tensorflow as tf print('''TensorFlow version:''', tf.__version__) print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU'''))) print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU'''))) except ImportError: print('''TensorFlow version:''', None)
351
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case_ : """simple docstring""" def __init__(self: Optional[int] , __UpperCAmelCase: int , __UpperCAmelCase: List[Any]=13 , __UpperCAmelCase: Any=30 , __UpperCAmelCase: List[str]=2 , __UpperCAmelCase: Optional[int]=3 , __UpperCAmelCase: Tuple=True , __UpperCAmelCase: str=True , __UpperCAmelCase: int=32 , __UpperCAmelCase: Tuple=5 , __UpperCAmelCase: Optional[Any]=4 , __UpperCAmelCase: Dict=37 , __UpperCAmelCase: List[Any]="gelu" , __UpperCAmelCase: List[Any]=0.1 , __UpperCAmelCase: Any=0.1 , __UpperCAmelCase: Optional[Any]=10 , __UpperCAmelCase: str=0.02 , __UpperCAmelCase: Any=3 , __UpperCAmelCase: Tuple=0.6 , __UpperCAmelCase: str=None , ) -> List[Any]: '''simple docstring''' __a : int = parent __a : Any = batch_size __a : int = image_size __a : Tuple = patch_size __a : str = num_channels __a : List[Any] = is_training __a : Tuple = use_labels __a : str = hidden_size __a : List[Any] = num_hidden_layers __a : str = num_attention_heads __a : Any = intermediate_size __a : str = hidden_act __a : Union[str, Any] = hidden_dropout_prob __a : Optional[int] = attention_probs_dropout_prob __a : Tuple = type_sequence_label_size __a : Any = initializer_range __a : Dict = mask_ratio __a : Union[str, Any] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __a : Any = (image_size // patch_size) ** 2 __a : Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def UpperCAmelCase__ (self: Any ) -> str: '''simple docstring''' __a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Optional[Any] = None if self.use_labels: __a : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ (self: Union[str, Any] ) -> Optional[int]: '''simple docstring''' return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def UpperCAmelCase__ (self: List[Any] , __UpperCAmelCase: str , __UpperCAmelCase: Tuple , __UpperCAmelCase: List[str] ) -> List[str]: '''simple docstring''' __a : str = ViTMAEModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __a : int = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ (self: Tuple , __UpperCAmelCase: Dict , __UpperCAmelCase: Tuple , __UpperCAmelCase: Dict ) -> Dict: '''simple docstring''' __a : Optional[Any] = ViTMAEForPreTraining(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __a : List[str] = model(__UpperCAmelCase ) __a : Union[str, Any] = (self.image_size // self.patch_size) ** 2 __a : Optional[int] = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images __a : Optional[Any] = 1 __a : int = ViTMAEForPreTraining(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __a : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a : Optional[int] = model(__UpperCAmelCase ) __a : List[Any] = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def UpperCAmelCase__ (self: Optional[int] ) -> Optional[Any]: '''simple docstring''' __a : List[Any] = self.prepare_config_and_inputs() __a , __a , __a : Dict = config_and_inputs __a : Union[str, Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): """simple docstring""" snake_case__ = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () snake_case__ = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {} snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def UpperCAmelCase__ (self: int ) -> Dict: '''simple docstring''' __a : List[str] = ViTMAEModelTester(self ) __a : str = ConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase , hidden_size=37 ) def UpperCAmelCase__ (self: Tuple ) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="ViTMAE does not use inputs_embeds" ) def UpperCAmelCase__ (self: str ) -> Optional[Any]: '''simple docstring''' pass def UpperCAmelCase__ (self: Dict ) -> str: '''simple docstring''' __a , __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Tuple = model_class(__UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCAmelCase , nn.Linear ) ) def UpperCAmelCase__ (self: Dict ) -> Tuple: '''simple docstring''' __a , __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Any = model_class(__UpperCAmelCase ) __a : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : int = ["pixel_values"] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) def UpperCAmelCase__ (self: Any ) -> Optional[int]: '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def UpperCAmelCase__ (self: List[str] ) -> Tuple: '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__UpperCAmelCase ) def UpperCAmelCase__ (self: Dict , __UpperCAmelCase: int , __UpperCAmelCase: Dict , __UpperCAmelCase: str ) -> Dict: '''simple docstring''' np.random.seed(2 ) __a : Union[str, Any] = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) __a : List[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __a : Tuple = torch.from_numpy(__UpperCAmelCase ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __a : Union[str, Any] = pt_noise super().check_pt_tf_models(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def UpperCAmelCase__ (self: str ) -> Dict: '''simple docstring''' __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Union[str, Any] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __a : Any = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __a : Dict = outputs[0].cpu().numpy() __a : str = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) __a : Any = model_class.from_pretrained(__UpperCAmelCase ) model.to(__UpperCAmelCase ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __a : Optional[int] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) # Make sure we don't have nans __a : Dict = after_outputs[0].cpu().numpy() __a : str = 0 __a : str = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__UpperCAmelCase , 1E-5 ) @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def UpperCAmelCase__ (self: Union[str, Any] ) -> Any: '''simple docstring''' pass @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def UpperCAmelCase__ (self: Optional[int] ) -> Dict: '''simple docstring''' pass @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def UpperCAmelCase__ (self: Optional[Any] ) -> List[str]: '''simple docstring''' pass @unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load" ) def UpperCAmelCase__ (self: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCAmelCase__ (self: List[str] ) -> List[Any]: '''simple docstring''' pass @slow def UpperCAmelCase__ (self: Tuple ) -> int: '''simple docstring''' for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Tuple = ViTMAEModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def a_ () -> Optional[Any]: """simple docstring""" __a : List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class snake_case_ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase__ (self: Optional[int] ) -> List[str]: '''simple docstring''' return ViTImageProcessor.from_pretrained("facebook/vit-mae-base" ) if is_vision_available() else None @slow def UpperCAmelCase__ (self: str ) -> Union[str, Any]: '''simple docstring''' np.random.seed(2 ) __a : int = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base" ).to(__UpperCAmelCase ) __a : Dict = self.default_image_processor __a : List[str] = prepare_img() __a : Tuple = image_processor(images=__UpperCAmelCase , return_tensors="pt" ).to(__UpperCAmelCase ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) __a : Optional[Any] = ViTMAEConfig() __a : str = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) __a : int = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): __a : Union[str, Any] = model(**__UpperCAmelCase , noise=torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase ) ) # verify the logits __a : Optional[Any] = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) __a : Any = torch.tensor( [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(__UpperCAmelCase ) , atol=1E-4 ) )
351
1
'''simple docstring''' from __future__ import annotations def A ( _UpperCAmelCase : float ,_UpperCAmelCase : float ,_UpperCAmelCase : float ,) -> tuple: '''simple docstring''' if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative in a semiconductor' ) elif hole_conc < 0: raise ValueError('Hole concentration cannot be negative in a semiconductor' ) elif intrinsic_conc < 0: raise ValueError( 'Intrinsic concentration cannot be negative in a semiconductor' ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
123
'''simple docstring''' def A ( _UpperCAmelCase : int = 1_0 ,_UpperCAmelCase : int = 1_0_0_0 ,_UpperCAmelCase : bool = True ) -> int: '''simple docstring''' assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)' ) return min_val if option else max_val def A ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int: '''simple docstring''' return int((number_a + number_a) / 2 ) def A ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> None: '''simple docstring''' assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)' ) if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value' ) def answer(_UpperCAmelCase : int ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...' ) __lowerCAmelCase : Union[str, Any] = lower __lowerCAmelCase : List[Any] = higher __lowerCAmelCase : List[str] = [] while True: __lowerCAmelCase : Union[str, Any] = get_avg(_UpperCAmelCase ,_UpperCAmelCase ) last_numbers.append(_UpperCAmelCase ) if answer(_UpperCAmelCase ) == "low": __lowerCAmelCase : List[Any] = number elif answer(_UpperCAmelCase ) == "high": __lowerCAmelCase : Optional[Any] = number else: break print(F"""guess the number : {last_numbers[-1]}""" ) print(F"""details : {last_numbers!s}""" ) def A ( ) -> None: '''simple docstring''' __lowerCAmelCase : int = int(input('Enter lower value : ' ).strip() ) __lowerCAmelCase : Optional[Any] = int(input('Enter high value : ' ).strip() ) __lowerCAmelCase : int = int(input('Enter value to guess : ' ).strip() ) guess_the_number(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if __name__ == "__main__": main()
123
1
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_12, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __UpperCamelCase ( lowercase__ : str ) -> Union[str, Any]: '''simple docstring''' if string == "True": return True elif string == "False": return False else: raise ValueError(f'could not parse string as bool {string}' ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
600
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class __a ( ctypes.Structure ): # _fields is a specific attr expected by ctypes __snake_case : Optional[Any] = [("""size""", ctypes.c_int), ("""visible""", ctypes.c_byte)] def __UpperCamelCase ( ) -> Optional[Any]: '''simple docstring''' if os.name == "nt": lowerCAmelCase_ : str = CursorInfo() lowerCAmelCase_ : Dict = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) lowerCAmelCase_ : str = False ctypes.windll.kernelaa.SetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) elif os.name == "posix": sys.stdout.write("""\033[?25l""" ) sys.stdout.flush() def __UpperCamelCase ( ) -> int: '''simple docstring''' if os.name == "nt": lowerCAmelCase_ : int = CursorInfo() lowerCAmelCase_ : int = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) lowerCAmelCase_ : Tuple = True ctypes.windll.kernelaa.SetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) elif os.name == "posix": sys.stdout.write("""\033[?25h""" ) sys.stdout.flush() @contextmanager def __UpperCamelCase ( ) -> List[Any]: '''simple docstring''' try: hide_cursor() yield finally: show_cursor()
600
1
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def __A(lowerCAmelCase ) -> List[str]: """simple docstring""" if "model" in orig_key: _UpperCamelCase = orig_key.replace("""model.""" , """""" ) if "norm1" in orig_key: _UpperCamelCase = orig_key.replace("""norm1""" , """attention.output.LayerNorm""" ) if "norm2" in orig_key: _UpperCamelCase = orig_key.replace("""norm2""" , """output.LayerNorm""" ) if "norm" in orig_key: _UpperCamelCase = orig_key.replace("""norm""" , """LayerNorm""" ) if "transformer" in orig_key: _UpperCamelCase = orig_key.split(""".""" )[0].split("""_""" )[-1] _UpperCamelCase = orig_key.replace(F'transformer_{layer_num}' , F'encoder.layer.{layer_num}' ) if "mha.attn" in orig_key: _UpperCamelCase = orig_key.replace("""mha.attn""" , """attention.self""" ) if "mha" in orig_key: _UpperCamelCase = orig_key.replace("""mha""" , """attention""" ) if "W_q" in orig_key: _UpperCamelCase = orig_key.replace("""W_q""" , """self.query""" ) if "W_k" in orig_key: _UpperCamelCase = orig_key.replace("""W_k""" , """self.key""" ) if "W_v" in orig_key: _UpperCamelCase = orig_key.replace("""W_v""" , """self.value""" ) if "ff1" in orig_key: _UpperCamelCase = orig_key.replace("""ff1""" , """intermediate.dense""" ) if "ff2" in orig_key: _UpperCamelCase = orig_key.replace("""ff2""" , """output.dense""" ) if "ff" in orig_key: _UpperCamelCase = orig_key.replace("""ff""" , """output.dense""" ) if "mlm_class" in orig_key: _UpperCamelCase = orig_key.replace("""mlm.mlm_class""" , """cls.predictions.decoder""" ) if "mlm" in orig_key: _UpperCamelCase = orig_key.replace("""mlm""" , """cls.predictions.transform""" ) if "cls" not in orig_key: _UpperCamelCase = """yoso.""" + orig_key return orig_key def __A(lowerCAmelCase , lowerCAmelCase ) -> List[str]: """simple docstring""" for key in orig_state_dict.copy().keys(): _UpperCamelCase = orig_state_dict.pop(lowerCAmelCase ) if ("pooler" in key) or ("sen_class" in key): continue else: _UpperCamelCase = val _UpperCamelCase = orig_state_dict["""cls.predictions.decoder.bias"""] _UpperCamelCase = torch.arange(lowerCAmelCase ).expand((1, -1) ) + 2 return orig_state_dict def __A(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Optional[int]: """simple docstring""" _UpperCamelCase = torch.load(lowerCAmelCase , map_location="""cpu""" )["""model_state_dict"""] _UpperCamelCase = YosoConfig.from_json_file(lowerCAmelCase ) _UpperCamelCase = YosoForMaskedLM(lowerCAmelCase ) _UpperCamelCase = convert_checkpoint_helper(config.max_position_embeddings , lowerCAmelCase ) print(model.load_state_dict(lowerCAmelCase ) ) model.eval() model.save_pretrained(lowerCAmelCase ) print(F'Checkpoint successfuly converted. Model saved at {pytorch_dump_path}' ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--pytorch_model_path", default=None, type=str, required=True, help="Path to YOSO pytorch checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The json file for YOSO model config.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) lowerCamelCase__ = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
202
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger() @dataclass class lowerCAmelCase__ : UpperCamelCase_ : nn.Module UpperCamelCase_ : List[nn.Module] = field(default_factory=__lowercase ) UpperCamelCase_ : list = field(default_factory=__lowercase ) def A_ ( self , a , a , a ) -> str: '''simple docstring''' _UpperCamelCase = len(list(m.modules() ) ) == 1 or isinstance(a , nn.Convad ) or isinstance(a , nn.BatchNormad ) if has_not_submodules: self.traced.append(a ) def __call__( self , a ) -> Optional[int]: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a ) [x.remove() for x in self.handles] return self @property def A_ ( self ) -> Optional[int]: '''simple docstring''' return list(filter(lambda a : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class lowerCAmelCase__ : UpperCamelCase_ : nn.Module UpperCamelCase_ : nn.Module UpperCamelCase_ : int = 0 UpperCamelCase_ : List = field(default_factory=__lowercase ) UpperCamelCase_ : List = field(default_factory=__lowercase ) def __call__( self , a ) -> List[Any]: '''simple docstring''' _UpperCamelCase = Tracker(self.dest )(a ).parametrized _UpperCamelCase = Tracker(self.src )(a ).parametrized _UpperCamelCase = list(filter(lambda a : type(a ) not in self.src_skip , a ) ) _UpperCamelCase = list(filter(lambda a : type(a ) not in self.dest_skip , a ) ) if len(a ) != len(a ): raise Exception( F'Numbers of operations are different. Source module has {len(a )} operations while' F' destination module has {len(a )}.' ) for dest_m, src_m in zip(a , a ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'Transfered from={src_m} to={dest_m}' ) def __A(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = True ) -> Optional[Any]: """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): _UpperCamelCase = timm.create_model(lowerCAmelCase , pretrained=lowerCAmelCase ).eval() _UpperCamelCase = ResNetForImageClassification(lowerCAmelCase ).eval() _UpperCamelCase = ModuleTransfer(src=lowerCAmelCase , dest=lowerCAmelCase ) _UpperCamelCase = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(lowerCAmelCase ) assert torch.allclose(from_model(lowerCAmelCase ) , our_model(lowerCAmelCase ).logits ), "The model logits don't match the original one." _UpperCamelCase = F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=lowerCAmelCase , ) # we can use the convnext one _UpperCamelCase = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=lowerCAmelCase , ) print(F'Pushed {checkpoint_name}' ) def __A(lowerCAmelCase , lowerCAmelCase = None , lowerCAmelCase = True ) -> Tuple: """simple docstring""" _UpperCamelCase = """imagenet-1k-id2label.json""" _UpperCamelCase = 1_0_0_0 _UpperCamelCase = (1, num_labels) _UpperCamelCase = """huggingface/label-files""" _UpperCamelCase = num_labels _UpperCamelCase = json.load(open(hf_hub_download(lowerCAmelCase , lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) _UpperCamelCase = {int(lowerCAmelCase ): v for k, v in idalabel.items()} _UpperCamelCase = idalabel _UpperCamelCase = {v: k for k, v in idalabel.items()} _UpperCamelCase = partial(lowerCAmelCase , num_labels=lowerCAmelCase , idalabel=lowerCAmelCase , labelaid=lowerCAmelCase ) _UpperCamelCase = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(lowerCAmelCase , names_to_config[model_name] , lowerCAmelCase , lowerCAmelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return config, expected_shape if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) lowerCamelCase__ = parser.parse_args() lowerCamelCase__ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
202
1
def _SCREAMING_SNAKE_CASE ( __lowercase : Any , __lowercase : int ) -> int: """simple docstring""" return number | (1 << position) def _SCREAMING_SNAKE_CASE ( __lowercase : Any , __lowercase : Optional[int] ) -> int: """simple docstring""" return number & ~(1 << position) def _SCREAMING_SNAKE_CASE ( __lowercase : Optional[Any] , __lowercase : Any ) -> int: """simple docstring""" return number ^ (1 << position) def _SCREAMING_SNAKE_CASE ( __lowercase : Optional[int] , __lowercase : List[str] ) -> bool: """simple docstring""" return ((number >> position) & 1) == 1 def _SCREAMING_SNAKE_CASE ( __lowercase : Optional[Any] , __lowercase : Dict ) -> int: """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
637
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline UpperCamelCase_ = { 'n_samples': 6_4, 'horizon': 3_2, 'num_inference_steps': 2_0, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std': True, 'scale': 0.1, 'eta': 0.0, 't_grad_cutoff': 2, 'device': 'cpu', } if __name__ == "__main__": UpperCamelCase_ = 'hopper-medium-v2' UpperCamelCase_ = gym.make(env_name) UpperCamelCase_ = ValueGuidedRLPipeline.from_pretrained( 'bglick13/hopper-medium-v2-value-function-hor32', env=env, ) env.seed(0) UpperCamelCase_ = env.reset() UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 1_0_0_0 UpperCamelCase_ = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy UpperCamelCase_ = pipeline(obs, planning_horizon=3_2) # execute action in environment UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = env.step(denorm_actions) UpperCamelCase_ = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( f'Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:' f' {total_score}' ) # save observations for rendering rollout.append(next_observation.copy()) UpperCamelCase_ = next_observation except KeyboardInterrupt: pass print(f'Total reward: {total_reward}')
132
0
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class A_ ( _a ): _UpperCAmelCase : jnp.ndarray @flax_register_to_config class A_ ( nn.Module , _a , _a ): _UpperCAmelCase : int = 32 _UpperCAmelCase : int = 4 _UpperCAmelCase : int = 4 _UpperCAmelCase : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _UpperCAmelCase : Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") _UpperCAmelCase : Union[bool, Tuple[bool]] = False _UpperCAmelCase : Tuple[int] = (320, 640, 1_280, 1_280) _UpperCAmelCase : int = 2 _UpperCAmelCase : Union[int, Tuple[int]] = 8 _UpperCAmelCase : Optional[Union[int, Tuple[int]]] = None _UpperCAmelCase : int = 1_280 _UpperCAmelCase : float = 0.0 _UpperCAmelCase : bool = False _UpperCAmelCase : jnp.dtype = jnp.floataa _UpperCAmelCase : bool = True _UpperCAmelCase : int = 0 _UpperCAmelCase : bool = False def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : List[Any]): # init input tensors __lowerCamelCase : List[str] = (1, self.in_channels, self.sample_size, self.sample_size) __lowerCamelCase : Optional[Any] = jnp.zeros(snake_case_ ,dtype=jnp.floataa) __lowerCamelCase : Tuple = jnp.ones((1,) ,dtype=jnp.intaa) __lowerCamelCase : Tuple = jnp.zeros((1, 1, self.cross_attention_dim) ,dtype=jnp.floataa) __lowerCamelCase , __lowerCamelCase : int = jax.random.split(snake_case_) __lowerCamelCase : str = {'params': params_rng, 'dropout': dropout_rng} return self.init(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_)["params"] def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[Any] = self.block_out_channels __lowerCamelCase : str = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( 'At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.') # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __lowerCamelCase : Optional[int] = self.num_attention_heads or self.attention_head_dim # input __lowerCamelCase : List[str] = nn.Conv( block_out_channels[0] ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) # time __lowerCamelCase : Optional[int] = FlaxTimesteps( block_out_channels[0] ,flip_sin_to_cos=self.flip_sin_to_cos ,freq_shift=self.config.freq_shift) __lowerCamelCase : List[str] = FlaxTimestepEmbedding(snake_case_ ,dtype=self.dtype) __lowerCamelCase : Optional[Any] = self.only_cross_attention if isinstance(snake_case_ ,snake_case_): __lowerCamelCase : Any = (only_cross_attention,) * len(self.down_block_types) if isinstance(snake_case_ ,snake_case_): __lowerCamelCase : int = (num_attention_heads,) * len(self.down_block_types) # down __lowerCamelCase : List[Any] = [] __lowerCamelCase : str = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types): __lowerCamelCase : Dict = output_channel __lowerCamelCase : Union[str, Any] = block_out_channels[i] __lowerCamelCase : Any = i == len(snake_case_) - 1 if down_block_type == "CrossAttnDownBlock2D": __lowerCamelCase : int = FlaxCrossAttnDownBlockaD( in_channels=snake_case_ ,out_channels=snake_case_ ,dropout=self.dropout ,num_layers=self.layers_per_block ,num_attention_heads=num_attention_heads[i] ,add_downsample=not is_final_block ,use_linear_projection=self.use_linear_projection ,only_cross_attention=only_cross_attention[i] ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) else: __lowerCamelCase : List[Any] = FlaxDownBlockaD( in_channels=snake_case_ ,out_channels=snake_case_ ,dropout=self.dropout ,num_layers=self.layers_per_block ,add_downsample=not is_final_block ,dtype=self.dtype ,) down_blocks.append(snake_case_) __lowerCamelCase : Any = down_blocks # mid __lowerCamelCase : int = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] ,dropout=self.dropout ,num_attention_heads=num_attention_heads[-1] ,use_linear_projection=self.use_linear_projection ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) # up __lowerCamelCase : Any = [] __lowerCamelCase : Dict = list(reversed(snake_case_)) __lowerCamelCase : Any = list(reversed(snake_case_)) __lowerCamelCase : Any = list(reversed(snake_case_)) __lowerCamelCase : Dict = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types): __lowerCamelCase : Union[str, Any] = output_channel __lowerCamelCase : str = reversed_block_out_channels[i] __lowerCamelCase : str = reversed_block_out_channels[min(i + 1 ,len(snake_case_) - 1)] __lowerCamelCase : int = i == len(snake_case_) - 1 if up_block_type == "CrossAttnUpBlock2D": __lowerCamelCase : int = FlaxCrossAttnUpBlockaD( in_channels=snake_case_ ,out_channels=snake_case_ ,prev_output_channel=snake_case_ ,num_layers=self.layers_per_block + 1 ,num_attention_heads=reversed_num_attention_heads[i] ,add_upsample=not is_final_block ,dropout=self.dropout ,use_linear_projection=self.use_linear_projection ,only_cross_attention=only_cross_attention[i] ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) else: __lowerCamelCase : Union[str, Any] = FlaxUpBlockaD( in_channels=snake_case_ ,out_channels=snake_case_ ,prev_output_channel=snake_case_ ,num_layers=self.layers_per_block + 1 ,add_upsample=not is_final_block ,dropout=self.dropout ,dtype=self.dtype ,) up_blocks.append(snake_case_) __lowerCamelCase : Dict = output_channel __lowerCamelCase : Any = up_blocks # out __lowerCamelCase : Tuple = nn.GroupNorm(num_groups=3_2 ,epsilon=1E-5) __lowerCamelCase : List[str] = nn.Conv( self.out_channels ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) def __call__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : str=None ,SCREAMING_SNAKE_CASE__ : Optional[Any] = True ,SCREAMING_SNAKE_CASE__ : List[Any] = False ,): # 1. time if not isinstance(snake_case_ ,jnp.ndarray): __lowerCamelCase : Optional[Any] = jnp.array([timesteps] ,dtype=jnp.intaa) elif isinstance(snake_case_ ,jnp.ndarray) and len(timesteps.shape) == 0: __lowerCamelCase : List[str] = timesteps.astype(dtype=jnp.floataa) __lowerCamelCase : Optional[Any] = jnp.expand_dims(snake_case_ ,0) __lowerCamelCase : Any = self.time_proj(snake_case_) __lowerCamelCase : Dict = self.time_embedding(snake_case_) # 2. pre-process __lowerCamelCase : List[Any] = jnp.transpose(snake_case_ ,(0, 2, 3, 1)) __lowerCamelCase : List[Any] = self.conv_in(snake_case_) # 3. down __lowerCamelCase : Optional[Any] = (sample,) for down_block in self.down_blocks: if isinstance(snake_case_ ,snake_case_): __lowerCamelCase , __lowerCamelCase : Dict = down_block(snake_case_ ,snake_case_ ,snake_case_ ,deterministic=not train) else: __lowerCamelCase , __lowerCamelCase : Tuple = down_block(snake_case_ ,snake_case_ ,deterministic=not train) down_block_res_samples += res_samples if down_block_additional_residuals is not None: __lowerCamelCase : Tuple = () for down_block_res_sample, down_block_additional_residual in zip( snake_case_ ,snake_case_): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) __lowerCamelCase : Union[str, Any] = new_down_block_res_samples # 4. mid __lowerCamelCase : Tuple = self.mid_block(snake_case_ ,snake_case_ ,snake_case_ ,deterministic=not train) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: __lowerCamelCase : str = down_block_res_samples[-(self.layers_per_block + 1) :] __lowerCamelCase : List[Any] = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(snake_case_ ,snake_case_): __lowerCamelCase : List[str] = up_block( snake_case_ ,temb=snake_case_ ,encoder_hidden_states=snake_case_ ,res_hidden_states_tuple=snake_case_ ,deterministic=not train ,) else: __lowerCamelCase : str = up_block(snake_case_ ,temb=snake_case_ ,res_hidden_states_tuple=snake_case_ ,deterministic=not train) # 6. post-process __lowerCamelCase : Optional[int] = self.conv_norm_out(snake_case_) __lowerCamelCase : List[Any] = nn.silu(snake_case_) __lowerCamelCase : Optional[Any] = self.conv_out(snake_case_) __lowerCamelCase : str = jnp.transpose(snake_case_ ,(0, 3, 1, 2)) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=snake_case_)
720
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class A_ : def lowerCAmelCase ( self : Tuple): torch.manual_seed(0) __lowerCamelCase : Optional[int] = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) __lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) __lowerCamelCase : List[str] = UNetaDConditionModel( sample_size=3_2 ,layers_per_block=1 ,block_out_channels=[3_2, 6_4] ,down_block_types=[ 'ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D', ] ,mid_block_type='UNetMidBlock2DSimpleCrossAttn' ,up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] ,in_channels=3 ,out_channels=6 ,cross_attention_dim=3_2 ,encoder_hid_dim=3_2 ,attention_head_dim=8 ,addition_embed_type='text' ,addition_embed_type_num_heads=2 ,cross_attention_norm='group_norm' ,resnet_time_scale_shift='scale_shift' ,act_fn='gelu' ,) unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests torch.manual_seed(0) __lowerCamelCase : Dict = DDPMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='squaredcos_cap_v2' ,beta_start=0.0001 ,beta_end=0.02 ,thresholding=SCREAMING_SNAKE_CASE__ ,dynamic_thresholding_ratio=0.95 ,sample_max_value=1.0 ,prediction_type='epsilon' ,variance_type='learned_range' ,) torch.manual_seed(0) __lowerCamelCase : List[Any] = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowerCAmelCase ( self : Any): torch.manual_seed(0) __lowerCamelCase : int = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) __lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) __lowerCamelCase : Any = UNetaDConditionModel( sample_size=3_2 ,layers_per_block=[1, 2] ,block_out_channels=[3_2, 6_4] ,down_block_types=[ 'ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D', ] ,mid_block_type='UNetMidBlock2DSimpleCrossAttn' ,up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] ,in_channels=6 ,out_channels=6 ,cross_attention_dim=3_2 ,encoder_hid_dim=3_2 ,attention_head_dim=8 ,addition_embed_type='text' ,addition_embed_type_num_heads=2 ,cross_attention_norm='group_norm' ,resnet_time_scale_shift='scale_shift' ,act_fn='gelu' ,class_embed_type='timestep' ,mid_block_scale_factor=1.414 ,time_embedding_act_fn='gelu' ,time_embedding_dim=3_2 ,) unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests torch.manual_seed(0) __lowerCamelCase : str = DDPMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='squaredcos_cap_v2' ,beta_start=0.0001 ,beta_end=0.02 ,thresholding=SCREAMING_SNAKE_CASE__ ,dynamic_thresholding_ratio=0.95 ,sample_max_value=1.0 ,prediction_type='epsilon' ,variance_type='learned_range' ,) torch.manual_seed(0) __lowerCamelCase : Union[str, Any] = DDPMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='squaredcos_cap_v2' ,beta_start=0.0001 ,beta_end=0.02 ,) torch.manual_seed(0) __lowerCamelCase : Any = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = self.get_dummy_components() __lowerCamelCase : Tuple = self.pipeline_class(**SCREAMING_SNAKE_CASE__) pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = inputs['prompt'] __lowerCamelCase : str = inputs['generator'] __lowerCamelCase : List[Any] = inputs['num_inference_steps'] __lowerCamelCase : Optional[Any] = inputs['output_type'] if "image" in inputs: __lowerCamelCase : Dict = inputs['image'] else: __lowerCamelCase : Optional[Any] = None if "mask_image" in inputs: __lowerCamelCase : Optional[int] = inputs['mask_image'] else: __lowerCamelCase : Dict = None if "original_image" in inputs: __lowerCamelCase : Dict = inputs['original_image'] else: __lowerCamelCase : Optional[Any] = None __lowerCamelCase , __lowerCamelCase : Optional[Any] = pipe.encode_prompt(SCREAMING_SNAKE_CASE__) # inputs with prompt converted to embeddings __lowerCamelCase : Union[str, Any] = { 'prompt_embeds': prompt_embeds, 'negative_prompt_embeds': negative_prompt_embeds, 'generator': generator, 'num_inference_steps': num_inference_steps, 'output_type': output_type, } if image is not None: __lowerCamelCase : List[str] = image if mask_image is not None: __lowerCamelCase : List[Any] = mask_image if original_image is not None: __lowerCamelCase : Optional[Any] = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = pipe(**SCREAMING_SNAKE_CASE__)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.pipeline_class.from_pretrained(SCREAMING_SNAKE_CASE__) pipe_loaded.to(SCREAMING_SNAKE_CASE__) pipe_loaded.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) is None ,F"`{optional_component}` did not stay set to None after loading." ,) __lowerCamelCase : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = inputs['generator'] __lowerCamelCase : Any = inputs['num_inference_steps'] __lowerCamelCase : List[str] = inputs['output_type'] # inputs with prompt converted to embeddings __lowerCamelCase : Any = { 'prompt_embeds': prompt_embeds, 'negative_prompt_embeds': negative_prompt_embeds, 'generator': generator, 'num_inference_steps': num_inference_steps, 'output_type': output_type, } if image is not None: __lowerCamelCase : Optional[int] = image if mask_image is not None: __lowerCamelCase : int = mask_image if original_image is not None: __lowerCamelCase : int = original_image __lowerCamelCase : List[Any] = pipe_loaded(**SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Dict = np.abs(to_np(SCREAMING_SNAKE_CASE__) - to_np(SCREAMING_SNAKE_CASE__)).max() self.assertLess(SCREAMING_SNAKE_CASE__ ,1E-4) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : str = self.get_dummy_components() __lowerCamelCase : Optional[int] = self.pipeline_class(**SCREAMING_SNAKE_CASE__) pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = pipe(**SCREAMING_SNAKE_CASE__)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.pipeline_class.from_pretrained(SCREAMING_SNAKE_CASE__) pipe_loaded.to(SCREAMING_SNAKE_CASE__) pipe_loaded.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests __lowerCamelCase : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = pipe_loaded(**SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : int = np.abs(to_np(SCREAMING_SNAKE_CASE__) - to_np(SCREAMING_SNAKE_CASE__)).max() self.assertLess(SCREAMING_SNAKE_CASE__ ,1E-4)
337
0
"""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 UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=18 , SCREAMING_SNAKE_CASE__=30 , SCREAMING_SNAKE_CASE__=400 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=True , ) -> Any: A__ = size if size is not None else {"height": 18, "width": 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = apply_ocr def snake_case__ ( self ) -> List[Any]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class UpperCamelCase__ ( _lowerCAmelCase , unittest.TestCase ): """simple docstring""" A__ : Any = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case__ ( self ) -> str: A__ = LayoutLMvaImageProcessingTester(self ) @property def snake_case__ ( self ) -> Any: return self.image_processor_tester.prepare_image_processor_dict() def snake_case__ ( self ) -> Optional[Any]: A__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_resize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "apply_ocr" ) ) def snake_case__ ( self ) -> Dict: A__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) A__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def snake_case__ ( self ) -> List[str]: pass def snake_case__ ( self ) -> Tuple: # Initialize image_processing A__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A__ = 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(encoding.boxes , SCREAMING_SNAKE_CASE__ ) # Test batched A__ = image_processing(SCREAMING_SNAKE_CASE__ , 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 ) -> Optional[int]: # Initialize image_processing A__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A__ = 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 A__ = image_processing(SCREAMING_SNAKE_CASE__ , 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 ) -> Tuple: # Initialize image_processing A__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A__ = 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 A__ = image_processing(SCREAMING_SNAKE_CASE__ , 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 ) -> int: # with apply_OCR = True A__ = LayoutLMvaImageProcessor() from datasets import load_dataset A__ = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) A__ = Image.open(ds[0]["file"] ).convert("RGB" ) A__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 A__ = [["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 A__ = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(encoding.boxes , SCREAMING_SNAKE_CASE__ ) # with apply_OCR = False A__ = LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE__ ) A__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
104
"""simple docstring""" import math from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { """facebook/data2vec-base-960h""": """https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json""", # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class UpperCamelCase__ ( _lowerCAmelCase ): """simple docstring""" A__ : List[str] = "data2vec-audio" def __init__( self , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.0_2 , SCREAMING_SNAKE_CASE__=1e-5 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=(512, 512, 512, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE__=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE__=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=19 , SCREAMING_SNAKE_CASE__=5 , SCREAMING_SNAKE_CASE__=0.0_5 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__="sum" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=256 , SCREAMING_SNAKE_CASE__=(512, 512, 512, 512, 1500) , SCREAMING_SNAKE_CASE__=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE__=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE__=512 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) A__ = hidden_size A__ = feat_extract_activation A__ = list(SCREAMING_SNAKE_CASE__ ) A__ = list(SCREAMING_SNAKE_CASE__ ) A__ = list(SCREAMING_SNAKE_CASE__ ) A__ = conv_bias A__ = num_conv_pos_embeddings A__ = num_conv_pos_embedding_groups A__ = conv_pos_kernel_size A__ = len(self.conv_dim ) A__ = num_hidden_layers A__ = intermediate_size A__ = hidden_act A__ = num_attention_heads A__ = hidden_dropout A__ = attention_dropout A__ = activation_dropout A__ = feat_proj_dropout A__ = final_dropout A__ = layerdrop A__ = layer_norm_eps A__ = initializer_range A__ = vocab_size A__ = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==" " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =" f""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" f""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A__ = mask_time_prob A__ = mask_time_length A__ = mask_time_min_masks A__ = mask_feature_prob A__ = mask_feature_length A__ = mask_feature_min_masks # ctc loss A__ = ctc_loss_reduction A__ = ctc_zero_infinity # adapter A__ = add_adapter A__ = adapter_kernel_size A__ = adapter_stride A__ = num_adapter_layers A__ = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. A__ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. A__ = list(SCREAMING_SNAKE_CASE__ ) A__ = list(SCREAMING_SNAKE_CASE__ ) A__ = list(SCREAMING_SNAKE_CASE__ ) A__ = xvector_output_dim @property def snake_case__ ( self ) -> List[str]: return math.prod(self.conv_stride )
104
1
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 ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
718
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys SCREAMING_SNAKE_CASE : List[Any] = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") SCREAMING_SNAKE_CASE : Optional[int] = ( subprocess.check_output(F"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode("utf-8").split() ) SCREAMING_SNAKE_CASE : Any = "|".join(sys.argv[1:]) SCREAMING_SNAKE_CASE : Union[str, Any] = re.compile(rF"^({joined_dirs}).*?\.py$") SCREAMING_SNAKE_CASE : List[Any] = [x for x in modified_files if regex.match(x)] print(" ".join(relevant_modified_files), end="")
354
0
'''simple docstring''' import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _UpperCAmelCase : Tuple = logging.get_logger(__name__) _UpperCAmelCase : Dict = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } _UpperCAmelCase : str = { '''vocab_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'''}, '''merges_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'''}, '''tokenizer_config_file''': { '''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json''' }, } _UpperCAmelCase : Tuple = {'''facebook/blenderbot-3B''': 1_28} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _SCREAMING_SNAKE_CASE ( ): _A = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) _A = bs[:] _A = 0 for b in range(2**8 ): if b not in bs: bs.append(__snake_case ) cs.append(2**8 + n ) n += 1 _A = [chr(__snake_case ) for n in cs] return dict(zip(__snake_case , __snake_case ) ) def _SCREAMING_SNAKE_CASE ( __snake_case : Any ): _A = set() _A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A = char return pairs class lowercase_ ( _UpperCamelCase ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self : Optional[Any], UpperCamelCase__ : Any, UpperCamelCase__ : Dict, UpperCamelCase__ : Optional[int]="replace", UpperCamelCase__ : List[str]="<s>", UpperCamelCase__ : Any="</s>", UpperCamelCase__ : List[str]="</s>", UpperCamelCase__ : List[Any]="<s>", UpperCamelCase__ : Optional[Any]="<unk>", UpperCamelCase__ : Tuple="<pad>", UpperCamelCase__ : Optional[int]="<mask>", UpperCamelCase__ : List[str]=False, **UpperCamelCase__ : Optional[Any], ) -> Dict: _A = AddedToken(UpperCamelCase__, lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__, UpperCamelCase__ ) else bos_token _A = AddedToken(UpperCamelCase__, lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__, UpperCamelCase__ ) else eos_token _A = AddedToken(UpperCamelCase__, lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__, UpperCamelCase__ ) else sep_token _A = AddedToken(UpperCamelCase__, lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__, UpperCamelCase__ ) else cls_token _A = AddedToken(UpperCamelCase__, lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__, UpperCamelCase__ ) else unk_token _A = 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 _A = 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: _A = json.load(UpperCamelCase__ ) _A = {v: k for k, v in self.encoder.items()} _A = errors # how to handle errors in decoding _A = bytes_to_unicode() _A = {v: k for k, v in self.byte_encoder.items()} with open(UpperCamelCase__, encoding='utf-8' ) as merges_handle: _A = merges_handle.read().split('\n' )[1:-1] _A = [tuple(merge.split() ) for merge in bpe_merges] _A = dict(zip(UpperCamelCase__, range(len(UpperCamelCase__ ) ) ) ) _A = {} _A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _A = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def __UpperCAmelCase ( self : Union[str, Any] ) -> Dict: return len(self.encoder ) def __UpperCAmelCase ( self : List[Any] ) -> Tuple: return dict(self.encoder, **self.added_tokens_encoder ) def __UpperCAmelCase ( self : str, UpperCamelCase__ : Optional[int] ) -> Any: if token in self.cache: return self.cache[token] _A = tuple(UpperCamelCase__ ) _A = get_pairs(UpperCamelCase__ ) if not pairs: return token while True: _A = min(UpperCamelCase__, key=lambda UpperCamelCase__ : self.bpe_ranks.get(UpperCamelCase__, float('inf' ) ) ) if bigram not in self.bpe_ranks: break _A , _A = bigram _A = [] _A = 0 while i < len(UpperCamelCase__ ): try: _A = word.index(UpperCamelCase__, UpperCamelCase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A = 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 _A = tuple(UpperCamelCase__ ) _A = new_word if len(UpperCamelCase__ ) == 1: break else: _A = get_pairs(UpperCamelCase__ ) _A = ' '.join(UpperCamelCase__ ) _A = word return word def __UpperCAmelCase ( self : Dict, UpperCamelCase__ : int ) -> Optional[Any]: _A = [] for token in re.findall(self.pat, UpperCamelCase__ ): _A = ''.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 __UpperCAmelCase ( self : int, UpperCamelCase__ : Any ) -> Dict: return self.encoder.get(UpperCamelCase__, self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self : List[Any], UpperCamelCase__ : Any ) -> Optional[int]: return self.decoder.get(UpperCamelCase__ ) def __UpperCAmelCase ( self : int, UpperCamelCase__ : int ) -> Any: _A = ''.join(UpperCamelCase__ ) _A = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8', errors=self.errors ) return text def __UpperCAmelCase ( self : Any, UpperCamelCase__ : str, UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCamelCase__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _A = os.path.join( UpperCamelCase__, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _A = 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' ) _A = 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!' ) _A = token_index writer.write(' '.join(UpperCamelCase__ ) + '\n' ) index += 1 return vocab_file, merge_file def __UpperCAmelCase ( self : Tuple, UpperCamelCase__ : List[int], UpperCamelCase__ : Optional[List[int]] = None, UpperCamelCase__ : bool = False ) -> List[int]: 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 __UpperCAmelCase ( self : Tuple, UpperCamelCase__ : List[int], UpperCamelCase__ : Optional[List[int]] = None ) -> List[int]: _A = [self.sep_token_id] _A = [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 __UpperCAmelCase ( self : Dict, UpperCamelCase__ : Tuple, UpperCamelCase__ : List[Any]=False, **UpperCamelCase__ : int ) -> Tuple: _A = 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()): _A = ' ' + text return (text, kwargs) def __UpperCAmelCase ( self : List[str], UpperCamelCase__ : List[int], UpperCamelCase__ : Optional[List[int]] = None ) -> Any: return token_ids_a + [self.eos_token_id] def __UpperCAmelCase ( self : Any, UpperCamelCase__ : "Conversation" ) -> List[int]: _A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(' ' + text ) else: # Generated responses should contain them already. inputs.append(UpperCamelCase__ ) _A = ' '.join(UpperCamelCase__ ) _A = self.encode(UpperCamelCase__ ) if len(UpperCamelCase__ ) > self.model_max_length: _A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
107
"""simple docstring""" import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : int = logging.get_logger(__name__) a_ : Union[str, Any] = { '''facebook/encodec_24khz''': '''https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json''', '''facebook/encodec_48khz''': '''https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json''', } class __lowercase( lowercase__ ): '''simple docstring''' __a : Any = 'encodec' def __init__( self , __a=[1.5, 3.0, 6.0, 12.0, 24.0] , __a=24000 , __a=1 , __a=False , __a=None , __a=None , __a=128 , __a=32 , __a=1 , __a=[8, 5, 4, 2] , __a="weight_norm" , __a=7 , __a=7 , __a=3 , __a=2 , __a=True , __a="reflect" , __a=2 , __a=2 , __a=1.0 , __a=1024 , __a=None , __a=True , **__a , ): __lowerCamelCase : Optional[int] = target_bandwidths __lowerCamelCase : Dict = sampling_rate __lowerCamelCase : Tuple = audio_channels __lowerCamelCase : List[Any] = normalize __lowerCamelCase : List[str] = chunk_length_s __lowerCamelCase : Optional[int] = overlap __lowerCamelCase : List[str] = hidden_size __lowerCamelCase : Tuple = num_filters __lowerCamelCase : Optional[Any] = num_residual_layers __lowerCamelCase : List[Any] = upsampling_ratios __lowerCamelCase : int = norm_type __lowerCamelCase : str = kernel_size __lowerCamelCase : Tuple = last_kernel_size __lowerCamelCase : str = residual_kernel_size __lowerCamelCase : Tuple = dilation_growth_rate __lowerCamelCase : Any = use_causal_conv __lowerCamelCase : str = pad_mode __lowerCamelCase : List[str] = compress __lowerCamelCase : int = num_lstm_layers __lowerCamelCase : str = trim_right_ratio __lowerCamelCase : Optional[int] = codebook_size __lowerCamelCase : Any = codebook_dim if codebook_dim is not None else hidden_size __lowerCamelCase : Tuple = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}''' ) super().__init__(**__a ) @property def snake_case_ ( self ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def snake_case_ ( self ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def snake_case_ ( self ): __lowerCamelCase : str = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def snake_case_ ( self ): return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
594
0
def __magic_name__( __UpperCAmelCase = 3 , __UpperCAmelCase = 7 , __UpperCAmelCase = 100_0000 ) -> int: '''simple docstring''' _lowerCamelCase = 0 _lowerCamelCase = 1 for current_denominator in range(1 , limit + 1 ): _lowerCamelCase = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: _lowerCamelCase = current_numerator _lowerCamelCase = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=100_0000))
708
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split() _lowerCamelCase = dict(zip(A_ , range(len(A_ ) ) ) ) _lowerCamelCase = { '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', } _lowerCamelCase = { '''feature_size''': 1, '''padding_value''': 0.0, '''sampling_rate''': 1_60_00, '''return_attention_mask''': False, '''do_normalize''': True, } _lowerCamelCase = tempfile.mkdtemp() _lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _lowerCamelCase = os.path.join(self.tmpdirname , A_ ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) with open(self.feature_extraction_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) # load decoder from hub _lowerCamelCase = '''hf-internal-testing/ngram-beam-search-decoder''' def UpperCamelCase_ ( self , **A_ ) -> str: """simple docstring""" _lowerCamelCase = self.add_kwargs_tokens_map.copy() kwargs.update(A_ ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase_ ( self , **A_ ) -> Optional[Any]: """simple docstring""" return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase_ ( self , **A_ ) -> int: """simple docstring""" return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) processor.save_pretrained(self.tmpdirname ) _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , A_ ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , A_ ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , A_ ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(['''xx'''] ) with self.assertRaisesRegex(A_ , '''include''' ): WavaVecaProcessorWithLM( tokenizer=A_ , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = floats_list((3, 10_00) ) _lowerCamelCase = feature_extractor(A_ , return_tensors='''np''' ) _lowerCamelCase = processor(A_ , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = '''This is a test string''' _lowerCamelCase = processor(text=A_ ) _lowerCamelCase = tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self , A_=(2, 10, 16) , A_=77 ) -> Optional[Any]: """simple docstring""" np.random.seed(A_ ) return np.random.rand(*A_ ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits(shape=(10, 16) , seed=13 ) _lowerCamelCase = processor.decode(A_ ) _lowerCamelCase = decoder.decode_beams(A_ )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual('''</s> <s> </s>''' , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ['''fork'''], ['''spawn''']] ) def UpperCamelCase_ ( self , A_ ) -> int: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: _lowerCamelCase = processor.batch_decode(A_ ) else: with get_context(A_ ).Pool() as pool: _lowerCamelCase = processor.batch_decode(A_ , A_ ) _lowerCamelCase = list(A_ ) with get_context('''fork''' ).Pool() as p: _lowerCamelCase = decoder.decode_beams_batch(A_ , A_ ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(A_ , decoded_processor.text ) self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] , decoded_processor.text ) self.assertListEqual(A_ , decoded_processor.logit_score ) self.assertListEqual(A_ , decoded_processor.lm_score ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = 15 _lowerCamelCase = -20.0 _lowerCamelCase = -4.0 _lowerCamelCase = processor.batch_decode( A_ , beam_width=A_ , beam_prune_logp=A_ , token_min_logp=A_ , ) _lowerCamelCase = decoded_processor_out.text _lowerCamelCase = list(A_ ) with get_context('''fork''' ).Pool() as pool: _lowerCamelCase = decoder.decode_beams_batch( A_ , A_ , beam_width=A_ , beam_prune_logp=A_ , token_min_logp=A_ , ) _lowerCamelCase = [d[0][0] for d in decoded_decoder_out] _lowerCamelCase = [d[0][2] for d in decoded_decoder_out] _lowerCamelCase = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(A_ , A_ ) self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] , A_ ) self.assertTrue(np.array_equal(A_ , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , A_ , atol=1E-3 ) ) self.assertTrue(np.array_equal(A_ , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9474] , A_ , atol=1E-3 ) ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = 2.0 _lowerCamelCase = 5.0 _lowerCamelCase = -20.0 _lowerCamelCase = True _lowerCamelCase = processor.batch_decode( A_ , alpha=A_ , beta=A_ , unk_score_offset=A_ , lm_score_boundary=A_ , ) _lowerCamelCase = decoded_processor_out.text _lowerCamelCase = list(A_ ) decoder.reset_params( alpha=A_ , beta=A_ , unk_score_offset=A_ , lm_score_boundary=A_ , ) with get_context('''fork''' ).Pool() as pool: _lowerCamelCase = decoder.decode_beams_batch( A_ , A_ , ) _lowerCamelCase = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(A_ , A_ ) self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] , A_ ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] _lowerCamelCase = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() _lowerCamelCase = os.listdir(A_ ) _lowerCamelCase = ['''alphabet.json''', '''language_model'''] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(A_ , A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = snapshot_download('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained(A_ ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] _lowerCamelCase = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() _lowerCamelCase = os.listdir(A_ ) _lowerCamelCase = os.listdir(A_ ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(A_ , A_ ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = floats_list((3, 10_00) ) _lowerCamelCase = processor_wavaveca(A_ , return_tensors='''np''' ) _lowerCamelCase = processor_auto(A_ , return_tensors='''np''' ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = processor_wavaveca.batch_decode(A_ ) _lowerCamelCase = processor_auto.batch_decode(A_ ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , ) @staticmethod def UpperCamelCase_ ( A_ , A_ ) -> str: """simple docstring""" _lowerCamelCase = [d[key] for d in offsets] return retrieved_list def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = self._get_dummy_logits()[0] _lowerCamelCase = processor.decode(A_ , output_word_offsets=A_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(A_ , A_ ) ) self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''end_offset''' ) , [1, 3, 5] ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = processor.batch_decode(A_ , output_word_offsets=A_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(A_ , A_ ) ) self.assertListEqual( [''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) for o in outputs['''word_offsets''']] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''end_offset''' ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" import torch _lowerCamelCase = load_dataset('''common_voice''' , '''en''' , split='''train''' , streaming=A_ ) _lowerCamelCase = ds.cast_column('''audio''' , datasets.Audio(sampling_rate=1_60_00 ) ) _lowerCamelCase = iter(A_ ) _lowerCamelCase = next(A_ ) _lowerCamelCase = AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) _lowerCamelCase = WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train _lowerCamelCase = processor(sample['''audio''']['''array'''] , return_tensors='''pt''' ).input_values with torch.no_grad(): _lowerCamelCase = model(A_ ).logits.cpu().numpy() _lowerCamelCase = processor.decode(logits[0] , output_word_offsets=A_ ) _lowerCamelCase = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate _lowerCamelCase = [ { '''start_time''': d['''start_offset'''] * time_offset, '''end_time''': d['''end_offset'''] * time_offset, '''word''': d['''word'''], } for d in output['''word_offsets'''] ] _lowerCamelCase = '''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL''' # output words self.assertEqual(''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) , A_ ) self.assertEqual(''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) , output.text ) # output times _lowerCamelCase = torch.tensor(self.get_from_offsets(A_ , '''start_time''' ) ) _lowerCamelCase = torch.tensor(self.get_from_offsets(A_ , '''end_time''' ) ) # fmt: off _lowerCamelCase = torch.tensor([1.4199, 1.6599, 2.2599, 3.0, 3.24, 3.5999, 3.7999, 4.0999, 4.26, 4.94, 5.28, 5.6599, 5.78, 5.94, 6.32, 6.5399, 6.6599] ) _lowerCamelCase = torch.tensor([1.5399, 1.8999, 2.9, 3.16, 3.5399, 3.72, 4.0199, 4.1799, 4.76, 5.1599, 5.5599, 5.6999, 5.86, 6.1999, 6.38, 6.6199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(A_ , A_ , atol=0.01 ) ) self.assertTrue(torch.allclose(A_ , A_ , atol=0.01 ) )
638
0
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def a_ ( __magic_name__ ) -> Dict: """simple docstring""" snake_case : int = model.config snake_case : Any = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) snake_case : str = MBartConfig( is_decoder=__a , is_encoder_decoder=__a , add_cross_attention=__a , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=__a , add_final_layer_norm=__a , ) return encoder_config, decoder_config def a_ ( __magic_name__ ) -> int: """simple docstring""" if "encoder.model" in name: snake_case : Tuple = name.replace('''encoder.model''' , '''encoder''' ) if "decoder.model" in name: snake_case : int = name.replace('''decoder.model''' , '''decoder''' ) if "patch_embed.proj" in name: snake_case : Optional[Any] = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: snake_case : List[Any] = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if name.startswith('''encoder''' ): if "layers" in name: snake_case : str = '''encoder.''' + name if "attn.proj" in name: snake_case : Any = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name and "mask" not in name: snake_case : Union[str, Any] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: snake_case : Optional[Any] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: snake_case : Union[str, Any] = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: snake_case : str = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: snake_case : int = name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "encoder.norm.weight": snake_case : Optional[int] = '''encoder.layernorm.weight''' if name == "encoder.norm.bias": snake_case : Optional[Any] = '''encoder.layernorm.bias''' return name def a_ ( __magic_name__ , __magic_name__ ) -> Dict: """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case : List[str] = orig_state_dict.pop(__a ) if "qkv" in key: snake_case : Any = key.split('''.''' ) snake_case : List[Any] = int(key_split[3] ) snake_case : int = int(key_split[5] ) snake_case : Optional[Any] = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case : Dict = val[:dim, :] snake_case : Tuple = val[dim : dim * 2, :] snake_case : Optional[Any] = val[-dim:, :] else: snake_case : Optional[Any] = val[:dim] snake_case : Any = val[dim : dim * 2] snake_case : Optional[Any] = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: snake_case : List[Any] = val return orig_state_dict def a_ ( __magic_name__ , __magic_name__=None , __magic_name__=False ) -> str: """simple docstring""" snake_case : List[Any] = DonutModel.from_pretrained(__a ).eval() # load HuggingFace model snake_case : str = get_configs(__a ) snake_case : Optional[int] = DonutSwinModel(__a ) snake_case : Tuple = MBartForCausalLM(__a ) snake_case : int = VisionEncoderDecoderModel(encoder=__a , decoder=__a ) model.eval() snake_case : Any = original_model.state_dict() snake_case : Optional[int] = convert_state_dict(__a , __a ) model.load_state_dict(__a ) # verify results on scanned document snake_case : Any = load_dataset('''hf-internal-testing/example-documents''' ) snake_case : str = dataset['''test'''][0]['''image'''].convert('''RGB''' ) snake_case : List[Any] = XLMRobertaTokenizerFast.from_pretrained(__a , from_slow=__a ) snake_case : Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) snake_case : List[Any] = DonutProcessor(__a , __a ) snake_case : Any = processor(__a , return_tensors='''pt''' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": snake_case : str = '''<s_docvqa><s_question>{user_input}</s_question><s_answer>''' snake_case : Tuple = '''When is the coffee break?''' snake_case : List[Any] = task_prompt.replace('''{user_input}''' , __a ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": snake_case : Any = '''<s_rvlcdip>''' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: snake_case : int = '''<s_cord>''' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": snake_case : Any = '''s_cord-v2>''' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": snake_case : str = '''<s_zhtrainticket>''' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt snake_case : List[str] = '''hello world''' else: raise ValueError('''Model name not supported''' ) snake_case : Any = original_model.decoder.tokenizer(__a , add_special_tokens=__a , return_tensors='''pt''' )[ '''input_ids''' ] snake_case : Tuple = original_model.encoder.model.patch_embed(__a ) snake_case : Dict = model.encoder.embeddings(__a ) assert torch.allclose(__a , __a , atol=1e-3 ) # verify encoder hidden states snake_case : str = original_model.encoder(__a ) snake_case : Any = model.encoder(__a ).last_hidden_state assert torch.allclose(__a , __a , atol=1e-2 ) # verify decoder hidden states snake_case : int = original_model(__a , __a , __a ).logits snake_case : Tuple = model(__a , decoder_input_ids=__a ).logits assert torch.allclose(__a , __a , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F"Saving model and processor to {pytorch_dump_folder_path}" ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if push_to_hub: model.push_to_hub('''nielsr/''' + model_name.split('''/''' )[-1] , commit_message='''Update model''' ) processor.push_to_hub('''nielsr/''' + model_name.split('''/''' )[-1] , commit_message='''Update model''' ) if __name__ == "__main__": _a : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model and processor to the 🤗 hub.', ) _a : List[Any] = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
598
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/text-classification/requirements.txt""") UpperCAmelCase_ : str = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) @dataclass class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Train language if it is different from the evaluation language."} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_xnli''' , __a ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ : int = training_args.get_process_log_level() logger.setLevel(__a ) datasets.utils.logging.set_verbosity(__a ) transformers.utils.logging.set_verbosity(__a ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(f'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE_ : Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE_ : int = load_dataset( '''xnli''' , model_args.language , split='''train''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE_ : Any = load_dataset( '''xnli''' , model_args.train_language , split='''train''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = train_dataset.features['''label'''].names if training_args.do_eval: SCREAMING_SNAKE_CASE_ : Dict = load_dataset( '''xnli''' , model_args.language , split='''validation''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE_ : Tuple = eval_dataset.features['''label'''].names if training_args.do_predict: SCREAMING_SNAKE_CASE_ : Optional[int] = load_dataset( '''xnli''' , model_args.language , split='''test''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE_ : str = predict_dataset.features['''label'''].names # Labels SCREAMING_SNAKE_CASE_ : List[Any] = len(__a ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__a , idalabel={str(__a ): label for i, label in enumerate(__a )} , labelaid={label: i for i, label in enumerate(__a )} , finetuning_task='''xnli''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE_ : Any = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__a , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE_ : Any = '''max_length''' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE_ : Union[str, Any] = False def preprocess_function(__a ): # Tokenize the texts return tokenizer( examples['''premise'''] , examples['''hypothesis'''] , padding=__a , max_length=data_args.max_seq_length , truncation=__a , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = min(len(__a ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE_ : Optional[int] = train_dataset.select(range(__a ) ) with training_args.main_process_first(desc='''train dataset map pre-processing''' ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = train_dataset.map( __a , batched=__a , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on train dataset''' , ) # Log a few random samples from the training set: for index in random.sample(range(len(__a ) ) , 3 ): logger.info(f'Sample {index} of the training set: {train_dataset[index]}.' ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE_ : Dict = min(len(__a ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE_ : str = eval_dataset.select(range(__a ) ) with training_args.main_process_first(desc='''validation dataset map pre-processing''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = eval_dataset.map( __a , batched=__a , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on validation dataset''' , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE_ : Dict = min(len(__a ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE_ : List[str] = predict_dataset.select(range(__a ) ) with training_args.main_process_first(desc='''prediction dataset map pre-processing''' ): SCREAMING_SNAKE_CASE_ : int = predict_dataset.map( __a , batched=__a , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on prediction dataset''' , ) # Get the metric function SCREAMING_SNAKE_CASE_ : List[str] = evaluate.load('''xnli''' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__a ): SCREAMING_SNAKE_CASE_ : Any = p.predictions[0] if isinstance(p.predictions , __a ) else p.predictions SCREAMING_SNAKE_CASE_ : Tuple = np.argmax(__a , axis=1 ) return metric.compute(predictions=__a , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE_ : str = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE_ : List[Any] = DataCollatorWithPadding(__a , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # Initialize our Trainer SCREAMING_SNAKE_CASE_ : List[str] = Trainer( model=__a , args=__a , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__a , tokenizer=__a , data_collator=__a , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE_ : List[str] = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE_ : Dict = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE_ : List[str] = last_checkpoint SCREAMING_SNAKE_CASE_ : Any = trainer.train(resume_from_checkpoint=__a ) SCREAMING_SNAKE_CASE_ : List[Any] = train_result.metrics SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__a ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = min(__a , len(__a ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('''train''' , __a ) trainer.save_metrics('''train''' , __a ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ : List[str] = trainer.evaluate(eval_dataset=__a ) SCREAMING_SNAKE_CASE_ : List[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__a ) SCREAMING_SNAKE_CASE_ : str = min(__a , len(__a ) ) trainer.log_metrics('''eval''' , __a ) trainer.save_metrics('''eval''' , __a ) # Prediction if training_args.do_predict: logger.info('''*** Predict ***''' ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = trainer.predict(__a , metric_key_prefix='''predict''' ) SCREAMING_SNAKE_CASE_ : List[Any] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__a ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(__a , len(__a ) ) trainer.log_metrics('''predict''' , __a ) trainer.save_metrics('''predict''' , __a ) SCREAMING_SNAKE_CASE_ : Any = np.argmax(__a , axis=1 ) SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(training_args.output_dir , '''predictions.txt''' ) if trainer.is_world_process_zero(): with open(__a , '''w''' ) as writer: writer.write('''index\tprediction\n''' ) for index, item in enumerate(__a ): SCREAMING_SNAKE_CASE_ : str = label_list[item] writer.write(f'{index}\t{item}\n' ) if __name__ == "__main__": main()
512
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class _a ( unittest.TestCase ): '''simple docstring''' @slow def _A ( self ): """simple docstring""" a__ : int = AutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" , return_dict=__UpperCAmelCase ).to(__UpperCAmelCase ) a__ : Any = AutoTokenizer.from_pretrained("google/mt5-small" ) a__ : Optional[int] = tokenizer("Hello there" , return_tensors="pt" ).input_ids a__ : Tuple = tokenizer("Hi I am" , return_tensors="pt" ).input_ids a__ : Dict = model(input_ids.to(__UpperCAmelCase ) , labels=labels.to(__UpperCAmelCase ) ).loss a__ : Dict = -(labels.shape[-1] * loss.item()) a__ : Optional[int] = -8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
717
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class _a ( unittest.TestCase ): '''simple docstring''' A :Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def _A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): """simple docstring""" a__ : Tuple = hf_hub_download( repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) a__ : Dict = VideoClassificationPipeline(model=__UpperCAmelCase , image_processor=__UpperCAmelCase , top_k=2 ) a__ : Dict = [ example_video_filepath, "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4", ] return video_classifier, examples def _A ( self , __UpperCAmelCase , __UpperCAmelCase ): """simple docstring""" for example in examples: a__ : List[str] = video_classifier(__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ {"score": ANY(__UpperCAmelCase ), "label": ANY(__UpperCAmelCase )}, {"score": ANY(__UpperCAmelCase ), "label": ANY(__UpperCAmelCase )}, ] , ) @require_torch def _A ( self ): """simple docstring""" a__ : List[Any] = "hf-internal-testing/tiny-random-VideoMAEForVideoClassification" a__ : Dict = VideoMAEFeatureExtractor( size={"shortest_edge": 10} , crop_size={"height": 10, "width": 10} ) a__ : Dict = pipeline( "video-classification" , model=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , frame_sampling_rate=4 ) a__ : List[str] = hf_hub_download(repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) a__ : List[Any] = video_classifier(__UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [{"score": 0.5_1_9_9, "label": "LABEL_0"}, {"score": 0.4_8_0_1, "label": "LABEL_1"}] , ) a__ : Optional[int] = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [{"score": 0.5_1_9_9, "label": "LABEL_0"}, {"score": 0.4_8_0_1, "label": "LABEL_1"}], [{"score": 0.5_1_9_9, "label": "LABEL_0"}, {"score": 0.4_8_0_1, "label": "LABEL_1"}], ] , ) @require_tf def _A ( self ): """simple docstring""" pass
207
0
'''simple docstring''' import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging lowerCAmelCase__ = '\\n\n' lowerCAmelCase__ = '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n' lowerCAmelCase__ = '\nArgs:\n model_id (str): model used for calculating Perplexity\n NOTE: Perplexity can only be calculated for causal language models.\n This includes models such as gpt2, causal variations of bert,\n causal versions of t5, and more (the full list can be found\n in the AutoModelForCausalLM documentation here:\n https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n input_texts (list of str): input text, each separate text snippet\n is one list entry.\n batch_size (int): the batch size to run texts through the model. Defaults to 16.\n add_start_token (bool): whether to add the start token to the texts,\n so the perplexity can include the probability of the first word. Defaults to True.\n device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n perplexity: dictionary containing the perplexity scores for the texts\n in the input list, as well as the mean perplexity. If one of the input texts is\n longer than the max input length of the model, then it is truncated to the\n max length for the perplexity computation.\nExamples:\n Example 1:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... add_start_token=False,\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 78.22\n >>> print(round(results["perplexities"][0], 2))\n 11.11\n\n Example 2:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = datasets.load_dataset("wikitext",\n ... "wikitext-2-raw-v1",\n ... split="test")["text"][:50] # doctest:+ELLIPSIS\n [...]\n >>> input_texts = [s for s in input_texts if s!=\'\']\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 60.35\n >>> print(round(results["perplexities"][0], 2))\n 81.12\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowercase (datasets.Metric ): def __UpperCamelCase ( self : Optional[int]): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'input_texts': datasets.Value('string'), }) , reference_urls=['https://huggingface.co/docs/transformers/perplexity'] , ) def __UpperCamelCase ( self : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int = 16 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[str, Any]=None): if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": UpperCamelCase__ : Any = 'cuda' else: UpperCamelCase__ : Optional[int] = 'cuda' if torch.cuda.is_available() else 'cpu' UpperCamelCase__ : List[Any] = AutoModelForCausalLM.from_pretrained(UpperCAmelCase_) UpperCamelCase__ : List[str] = model.to(UpperCAmelCase_) UpperCamelCase__ : Dict = AutoTokenizer.from_pretrained(UpperCAmelCase_) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: UpperCamelCase__ : int = list(tokenizer.special_tokens_map_extended.values()) # check that the model already has at least one special token defined assert ( len(UpperCAmelCase_) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'pad_token': existing_special_tokens[0]}) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" UpperCamelCase__ : Optional[Any] = model.config.max_length - 1 else: UpperCamelCase__ : int = model.config.max_length UpperCamelCase__ : Any = tokenizer( UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , return_tensors='pt' , return_attention_mask=UpperCAmelCase_ , ).to(UpperCAmelCase_) UpperCamelCase__ : Tuple = encodings['input_ids'] UpperCamelCase__ : Optional[Any] = encodings['attention_mask'] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1) , 1)), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1) , 2)), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." UpperCamelCase__ : Tuple = [] UpperCamelCase__ : Union[str, Any] = CrossEntropyLoss(reduction='none') for start_index in logging.tqdm(range(0 , len(UpperCAmelCase_) , UpperCAmelCase_)): UpperCamelCase__ : List[str] = min(start_index + batch_size , len(UpperCAmelCase_)) UpperCamelCase__ : Any = encoded_texts[start_index:end_index] UpperCamelCase__ : Any = attn_masks[start_index:end_index] if add_start_token: UpperCamelCase__ : Any = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0)).to(UpperCAmelCase_) UpperCamelCase__ : Optional[int] = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1) UpperCamelCase__ : Dict = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa).to(UpperCAmelCase_), attn_mask] , dim=1) UpperCamelCase__ : Union[str, Any] = encoded_batch with torch.no_grad(): UpperCamelCase__ : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_).logits UpperCamelCase__ : Optional[int] = out_logits[..., :-1, :].contiguous() UpperCamelCase__ : List[Any] = labels[..., 1:].contiguous() UpperCamelCase__ : Any = attn_mask[..., 1:].contiguous() UpperCamelCase__ : Dict = torch.expa( (loss_fct(shift_logits.transpose(1 , 2) , UpperCAmelCase_) * shift_attention_mask_batch).sum(1) / shift_attention_mask_batch.sum(1)) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(UpperCAmelCase_)}
596
'''simple docstring''' lowerCAmelCase__ = 'Alexander Joslin' import operator as op from .stack import Stack def __UpperCAmelCase ( lowerCamelCase_) -> int: UpperCamelCase__ : List[str] = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} UpperCamelCase__ : Stack[int] = Stack() UpperCamelCase__ : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(lowerCamelCase_)) elif i in operators: # RULE 2 operator_stack.push(lowerCamelCase_) elif i == ")": # RULE 4 UpperCamelCase__ : Optional[Any] = operator_stack.peek() operator_stack.pop() UpperCamelCase__ : Optional[Any] = operand_stack.peek() operand_stack.pop() UpperCamelCase__ : List[Any] = operand_stack.peek() operand_stack.pop() UpperCamelCase__ : List[Any] = operators[opr](lowerCamelCase_ , lowerCamelCase_) operand_stack.push(lowerCamelCase_) # RULE 5 return operand_stack.peek() if __name__ == "__main__": lowerCAmelCase__ = '(5 + ((4 * 2) * (2 + 3)))' # answer = 45 print(f'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
596
1
'''simple docstring''' import torch from diffusers import StableDiffusionPipeline UpperCAmelCase : int = 'path-to-your-trained-model' UpperCAmelCase : Dict = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('cuda') UpperCAmelCase : Dict = 'A photo of sks dog in a bucket' UpperCAmelCase : Optional[int] = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0] image.save('dog-bucket.png')
707
'''simple docstring''' import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowerCamelCase (unittest.TestCase ): @slow def UpperCAmelCase_ ( self ) -> int: """simple docstring""" _snake_case : Tuple = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) _snake_case : Any = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _snake_case : List[str] = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids _snake_case : Dict = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids _snake_case : Any = shift_tokens_right(lowercase__ , model.config.pad_token_id , model.config.decoder_start_token_id ) _snake_case : Any = model(lowercase__ , decoder_input_ids=lowercase__ ).logits _snake_case : Tuple = optax.softmax_cross_entropy(lowercase__ , onehot(lowercase__ , logits.shape[-1] ) ).mean() _snake_case : Tuple = -(labels.shape[-1] * loss.item()) _snake_case : Union[str, Any] = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
47
0
"""simple docstring""" import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class UpperCAmelCase_ : @property def _UpperCamelCase ( self : Any ) -> Any: return self.get_dummy_input() @property def _UpperCamelCase ( self : List[str] ) -> Dict: if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.''' ) def _UpperCamelCase ( self : int , __UpperCamelCase : List[str]=True , __UpperCamelCase : List[str]=False , __UpperCamelCase : int=False , __UpperCamelCase : List[Any]=False , ) -> List[Any]: _UpperCamelCase = 4 _UpperCamelCase = 32 _UpperCamelCase = (32, 32) _UpperCamelCase = torch.manual_seed(0 ) _UpperCamelCase = torch.device(__UpperCamelCase ) _UpperCamelCase = (batch_size, num_channels) + sizes _UpperCamelCase = randn_tensor(__UpperCamelCase , generator=__UpperCamelCase , device=__UpperCamelCase ) _UpperCamelCase = {'''hidden_states''': hidden_states} if include_temb: _UpperCamelCase = 128 _UpperCamelCase = randn_tensor((batch_size, temb_channels) , generator=__UpperCamelCase , device=__UpperCamelCase ) if include_res_hidden_states_tuple: _UpperCamelCase = torch.manual_seed(1 ) _UpperCamelCase = (randn_tensor(__UpperCamelCase , generator=__UpperCamelCase , device=__UpperCamelCase ),) if include_encoder_hidden_states: _UpperCamelCase = floats_tensor((batch_size, 32, 32) ).to(__UpperCamelCase ) if include_skip_sample: _UpperCamelCase = randn_tensor(((batch_size, 3) + sizes) , generator=__UpperCamelCase , device=__UpperCamelCase ) return dummy_input def _UpperCamelCase ( self : List[Any] ) -> int: _UpperCamelCase = { '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 128, } if self.block_type == "up": _UpperCamelCase = 32 if self.block_type == "mid": init_dict.pop('''out_channels''' ) _UpperCamelCase = self.dummy_input return init_dict, inputs_dict def _UpperCamelCase ( self : Any , __UpperCamelCase : Optional[Any] ) -> List[str]: _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**__UpperCamelCase ) unet_block.to(__UpperCamelCase ) unet_block.eval() with torch.no_grad(): _UpperCamelCase = unet_block(**__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ): _UpperCamelCase = output[0] self.assertEqual(output.shape , self.output_shape ) _UpperCamelCase = output[0, -1, -3:, -3:] _UpperCamelCase = torch.tensor(__UpperCamelCase ).to(__UpperCamelCase ) assert torch_all_close(output_slice.flatten() , __UpperCamelCase , atol=5E-3 ) @unittest.skipIf(torch_device == '''mps''' , '''Training is not supported in mps''' ) def _UpperCamelCase ( self : Optional[int] ) -> List[str]: _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**__UpperCamelCase ) model.to(__UpperCamelCase ) model.train() _UpperCamelCase = model(**__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ): _UpperCamelCase = output[0] _UpperCamelCase = torch.device(__UpperCamelCase ) _UpperCamelCase = randn_tensor(output.shape , device=__UpperCamelCase ) _UpperCamelCase = torch.nn.functional.mse_loss(__UpperCamelCase , __UpperCamelCase ) loss.backward()
420
"""simple docstring""" from queue import PriorityQueue from typing import Any import numpy as np def lowercase ( a__ : dict , a__ : str , a__ : set , a__ : set , a__ : dict , a__ : dict , a__ : PriorityQueue , a__ : dict , a__ : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue _UpperCamelCase = cst_fwd.get(a__ , np.inf ) _UpperCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) _UpperCamelCase = new_cost_f _UpperCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: _UpperCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowercase ( a__ : str , a__ : str , a__ : dict , a__ : dict ) -> int: _UpperCamelCase = -1 _UpperCamelCase = set() _UpperCamelCase = set() _UpperCamelCase = {source: 0} _UpperCamelCase = {destination: 0} _UpperCamelCase = {source: None} _UpperCamelCase = {destination: None} _UpperCamelCase = PriorityQueue() _UpperCamelCase = PriorityQueue() _UpperCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): _UpperCamelCase , _UpperCamelCase = queue_forward.get() visited_forward.add(a__ ) _UpperCamelCase , _UpperCamelCase = queue_backward.get() visited_backward.add(a__ ) _UpperCamelCase = pass_and_relaxation( a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) _UpperCamelCase = pass_and_relaxation( a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: _UpperCamelCase = shortest_distance return shortest_path_distance UpperCAmelCase = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCAmelCase = { """B""": [["""E""", 1]], """C""": [["""B""", 1]], """D""": [["""C""", 1]], """F""": [["""D""", 1], ["""G""", 1]], """E""": [[None, np.inf]], """G""": [["""E""", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
420
1
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: snake_case = None snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """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""", }, """tokenizer_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/tokenizer.json""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/tokenizer.json""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/tokenizer.json""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/tokenizer.json""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/tokenizer.json""", }, } # TODO(PVP) - this should be removed in Transformers v5 snake_case = { """t5-small""": 5_12, """t5-base""": 5_12, """t5-large""": 5_12, """t5-3b""": 5_12, """t5-11b""": 5_12, } class lowerCAmelCase ( UpperCamelCase_ ): A_ : Any = VOCAB_FILES_NAMES A_ : str = PRETRAINED_VOCAB_FILES_MAP A_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : str = ["""input_ids""", """attention_mask"""] A_ : Optional[Any] = TaTokenizer A_ : List[int] = [] def __init__( self : Dict , a__ : Tuple=None , a__ : Union[str, Any]=None , a__ : Optional[int]="</s>" , a__ : Union[str, Any]="<unk>" , a__ : Union[str, Any]="<pad>" , a__ : Union[str, Any]=100 , a__ : Any=None , **a__ : Union[str, Any] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: lowerCAmelCase__ : Tuple = [F'''<extra_id_{i}>''' for i in range(a__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens lowerCAmelCase__ : Union[str, Any] = len(set(filter(lambda a__ : bool("extra_id_" in str(a__ ) ) , a__ ) ) ) 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" ) super().__init__( a__ , tokenizer_file=a__ , eos_token=a__ , unk_token=a__ , pad_token=a__ , extra_ids=a__ , additional_special_tokens=a__ , **a__ , ) lowerCAmelCase__ : Dict = vocab_file lowerCAmelCase__ : Dict = False if not self.vocab_file else True lowerCAmelCase__ : int = extra_ids @staticmethod def _A ( a__ : Tuple , a__ : Optional[int] , a__ : str ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: lowerCAmelCase__ : Dict = TaTokenizerFast.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." , a__ , ) return max_model_length def _A ( self : Tuple , a__ : str , a__ : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(a__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCAmelCase__ : Tuple = os.path.join( a__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a__ ): copyfile(self.vocab_file , a__ ) logger.info(F'''Copy vocab file to {out_vocab_file}''' ) return (out_vocab_file,) def _A ( self : Union[str, Any] , a__ : List[int] , a__ : Optional[List[int]] = None ): '''simple docstring''' lowerCAmelCase__ : List[Any] = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: lowerCAmelCase__ : int = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def _A ( self : List[Any] , a__ : List[int] , a__ : Optional[List[int]] = None ): '''simple docstring''' lowerCAmelCase__ : List[Any] = [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 _A ( self : Tuple ): '''simple docstring''' return list( set(filter(lambda a__ : bool(re.search(r"<extra_id_\d+>" , a__ ) ) is not None , self.additional_special_tokens ) ) ) def _A ( self : str ): '''simple docstring''' return [self.convert_tokens_to_ids(a__ ) for token in self.get_sentinel_tokens()]
701
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class lowerCAmelCase ( unittest.TestCase ): def _A ( self : List[str] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _A ( self : int ): '''simple docstring''' lowerCAmelCase__ : List[Any] = 1 lowerCAmelCase__ : Union[str, Any] = 3 lowerCAmelCase__ : Any = (32, 32) lowerCAmelCase__ : Dict = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(a__ ) return image @property def _A ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ : Union[str, 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") , cross_attention_dim=32 , ) return model @property def _A ( self : Optional[Any] ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def _A ( self : Optional[Any] ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ : List[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 , ) return CLIPTextModel(a__ ) @property def _A ( self : int ): '''simple docstring''' def extract(*a__ : List[Any] , **a__ : int ): class lowerCAmelCase : def __init__( self : Optional[int] ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = torch.ones([0] ) def _A ( self : str , a__ : str ): '''simple docstring''' self.pixel_values.to(a__ ) return self return Out() return extract def _A ( self : Any ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ : Union[str, Any] = self.dummy_cond_unet lowerCAmelCase__ : Union[str, Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=a__ , set_alpha_to_one=a__ , ) lowerCAmelCase__ : Optional[Any] = self.dummy_vae lowerCAmelCase__ : Tuple = self.dummy_text_encoder lowerCAmelCase__ : Dict = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk lowerCAmelCase__ : List[Any] = StableDiffusionPipeline( unet=a__ , scheduler=a__ , vae=a__ , text_encoder=a__ , tokenizer=a__ , safety_checker=a__ , feature_extractor=self.dummy_extractor , ) lowerCAmelCase__ : Dict = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) lowerCAmelCase__ : List[str] = "A painting of a squirrel eating a burger" lowerCAmelCase__ : str = torch.Generator(device=a__ ).manual_seed(0 ) lowerCAmelCase__ : Optional[int] = sd_pipe([prompt] , generator=a__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) lowerCAmelCase__ : Optional[Any] = output.images lowerCAmelCase__ : Union[str, Any] = torch.Generator(device=a__ ).manual_seed(0 ) lowerCAmelCase__ : Optional[int] = sd_pipe( [prompt] , generator=a__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a__ , )[0] lowerCAmelCase__ : Any = image[0, -3:, -3:, -1] lowerCAmelCase__ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase__ : Any = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def _A ( self : Any ): '''simple docstring''' lowerCAmelCase__ : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ : int = self.dummy_cond_unet lowerCAmelCase__ : Optional[int] = PNDMScheduler(skip_prk_steps=a__ ) lowerCAmelCase__ : Optional[int] = self.dummy_vae lowerCAmelCase__ : Tuple = self.dummy_text_encoder lowerCAmelCase__ : List[str] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk lowerCAmelCase__ : List[str] = StableDiffusionPipeline( unet=a__ , scheduler=a__ , vae=a__ , text_encoder=a__ , tokenizer=a__ , safety_checker=a__ , feature_extractor=self.dummy_extractor , ) lowerCAmelCase__ : Optional[int] = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) lowerCAmelCase__ : Tuple = "A painting of a squirrel eating a burger" lowerCAmelCase__ : str = torch.Generator(device=a__ ).manual_seed(0 ) lowerCAmelCase__ : Optional[int] = sd_pipe([prompt] , generator=a__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) lowerCAmelCase__ : Union[str, Any] = output.images lowerCAmelCase__ : Tuple = torch.Generator(device=a__ ).manual_seed(0 ) lowerCAmelCase__ : Tuple = sd_pipe( [prompt] , generator=a__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a__ , )[0] lowerCAmelCase__ : Optional[Any] = image[0, -3:, -3:, -1] lowerCAmelCase__ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase__ : Optional[Any] = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def _A ( self : str ): '''simple docstring''' lowerCAmelCase__ : str = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=a__ ) assert isinstance(a__ , a__ ) assert isinstance(pipe.scheduler , a__ ) assert pipe.safety_checker is None lowerCAmelCase__ : List[Any] = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(a__ ) lowerCAmelCase__ : List[Any] = StableDiffusionPipeline.from_pretrained(a__ ) # sanity check that the pipeline still works assert pipe.safety_checker is None lowerCAmelCase__ : List[Any] = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def _A ( self : Optional[Any] ): '''simple docstring''' lowerCAmelCase__ : List[str] = self.dummy_cond_unet lowerCAmelCase__ : Tuple = PNDMScheduler(skip_prk_steps=a__ ) lowerCAmelCase__ : Dict = self.dummy_vae lowerCAmelCase__ : Optional[int] = self.dummy_text_encoder lowerCAmelCase__ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 lowerCAmelCase__ : List[Any] = unet.half() lowerCAmelCase__ : Dict = vae.half() lowerCAmelCase__ : List[str] = bert.half() # make sure here that pndm scheduler skips prk lowerCAmelCase__ : List[str] = StableDiffusionPipeline( unet=a__ , scheduler=a__ , vae=a__ , text_encoder=a__ , tokenizer=a__ , safety_checker=a__ , feature_extractor=self.dummy_extractor , ) lowerCAmelCase__ : str = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) lowerCAmelCase__ : Dict = "A painting of a squirrel eating a burger" lowerCAmelCase__ : Any = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class lowerCAmelCase ( unittest.TestCase ): def _A ( self : Dict ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : List[Any] ): '''simple docstring''' lowerCAmelCase__ : List[Any] = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a__ ) lowerCAmelCase__ : Any = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) lowerCAmelCase__ : Tuple = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) lowerCAmelCase__ : Any = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) lowerCAmelCase__ : List[str] = 40_0366_0346 lowerCAmelCase__ : int = 7 # without safety guidance (sld_guidance_scale = 0) lowerCAmelCase__ : Dict = torch.manual_seed(a__ ) lowerCAmelCase__ : List[str] = sd_pipe( [prompt] , generator=a__ , guidance_scale=a__ , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) lowerCAmelCase__ : List[Any] = output.images lowerCAmelCase__ : Optional[Any] = image[0, -3:, -3:, -1] lowerCAmelCase__ : Union[str, Any] = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) lowerCAmelCase__ : Tuple = torch.manual_seed(a__ ) lowerCAmelCase__ : Tuple = sd_pipe( [prompt] , generator=a__ , guidance_scale=a__ , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) lowerCAmelCase__ : List[Any] = output.images lowerCAmelCase__ : Union[str, Any] = image[0, -3:, -3:, -1] lowerCAmelCase__ : List[str] = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _A ( self : Any ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a__ ) lowerCAmelCase__ : str = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) lowerCAmelCase__ : Optional[Any] = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) lowerCAmelCase__ : int = "padme amidala taking a bath artwork, safe for work, no nudity" lowerCAmelCase__ : Union[str, Any] = 27_3497_1755 lowerCAmelCase__ : str = 7 lowerCAmelCase__ : Any = torch.manual_seed(a__ ) lowerCAmelCase__ : Dict = sd_pipe( [prompt] , generator=a__ , guidance_scale=a__ , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) lowerCAmelCase__ : Optional[Any] = output.images lowerCAmelCase__ : Any = image[0, -3:, -3:, -1] lowerCAmelCase__ : Optional[Any] = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 lowerCAmelCase__ : Optional[int] = torch.manual_seed(a__ ) lowerCAmelCase__ : Dict = sd_pipe( [prompt] , generator=a__ , guidance_scale=a__ , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) lowerCAmelCase__ : Optional[int] = output.images lowerCAmelCase__ : Union[str, Any] = image[0, -3:, -3:, -1] lowerCAmelCase__ : Union[str, Any] = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _A ( self : List[str] ): '''simple docstring''' lowerCAmelCase__ : Tuple = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) lowerCAmelCase__ : List[str] = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) lowerCAmelCase__ : Dict = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) lowerCAmelCase__ : Union[str, Any] = 10_4435_5234 lowerCAmelCase__ : Optional[int] = 12 lowerCAmelCase__ : Tuple = torch.manual_seed(a__ ) lowerCAmelCase__ : str = sd_pipe( [prompt] , generator=a__ , guidance_scale=a__ , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) lowerCAmelCase__ : Union[str, Any] = output.images lowerCAmelCase__ : int = image[0, -3:, -3:, -1] lowerCAmelCase__ : str = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 lowerCAmelCase__ : List[Any] = torch.manual_seed(a__ ) lowerCAmelCase__ : List[Any] = sd_pipe( [prompt] , generator=a__ , guidance_scale=a__ , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) lowerCAmelCase__ : List[Any] = output.images lowerCAmelCase__ : Optional[Any] = image[0, -3:, -3:, -1] lowerCAmelCase__ : int = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
568
0
import itertools import string from collections.abc import Generator, Iterable def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Iterable[str] ,lowerCAmelCase_ : int ) -> Generator[tuple[str, ...], None, None]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] =iter(lowerCAmelCase_ ) while True: SCREAMING_SNAKE_CASE_ : Union[str, Any] =tuple(itertools.islice(lowerCAmelCase_ ,lowerCAmelCase_ ) ) if not chunk: return yield chunk def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : int =''.join([c.upper() for c in dirty if c in string.ascii_letters] ) SCREAMING_SNAKE_CASE_ : List[str] ='' if len(lowerCAmelCase_ ) < 2: return dirty for i in range(len(lowerCAmelCase_ ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(lowerCAmelCase_ ) & 1: clean += "X" return clean def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ) -> list[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict ='ABCDEFGHIKLMNOPQRSTUVWXYZ' # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler SCREAMING_SNAKE_CASE_ : Any =[] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(lowerCAmelCase_ ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(lowerCAmelCase_ ) return table def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ,lowerCAmelCase_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple =generate_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] =prepare_input(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Any ='' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(lowerCAmelCase_ ,2 ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] =divmod(table.index(lowerCAmelCase_ ) ,5 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] =divmod(table.index(lowerCAmelCase_ ) ,5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ,lowerCAmelCase_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] =generate_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] ='' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(lowerCAmelCase_ ,2 ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any =divmod(table.index(lowerCAmelCase_ ) ,5 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int =divmod(table.index(lowerCAmelCase_ ) ,5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
220
import argparse import collections import json import os import re import string import sys import numpy as np __SCREAMING_SNAKE_CASE = re.compile(r'\b(a|an|the)\b', re.UNICODE) __SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] =argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.' ) parser.add_argument('data_file' ,metavar='data.json' ,help='Input data JSON file.' ) parser.add_argument('pred_file' ,metavar='pred.json' ,help='Model predictions.' ) parser.add_argument( '--out-file' ,'-o' ,metavar='eval.json' ,help='Write accuracy metrics to file (default is stdout).' ) parser.add_argument( '--na-prob-file' ,'-n' ,metavar='na_prob.json' ,help='Model estimates of probability of no answer.' ) parser.add_argument( '--na-prob-thresh' ,'-t' ,type=lowerCAmelCase_ ,default=1.0 ,help='Predict "" if no-answer probability exceeds this (default = 1.0).' ,) parser.add_argument( '--out-image-dir' ,'-p' ,metavar='out_images' ,default=lowerCAmelCase_ ,help='Save precision-recall curves to directory.' ) parser.add_argument('--verbose' ,'-v' ,action='store_true' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] ={} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE_ : Optional[Any] =bool(qa['answers']['text'] ) return qid_to_has_ans def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Any ) -> List[Any]: """simple docstring""" def remove_articles(lowerCAmelCase_ : Optional[Any] ): return ARTICLES_REGEX.sub(' ' ,lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ : Tuple ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE_ : Optional[int] =set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ : Optional[Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Any ) -> int: """simple docstring""" if not s: return [] return normalize_answer(lowerCAmelCase_ ).split() def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : str ) -> Any: """simple docstring""" return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Any ,lowerCAmelCase_ : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] =get_tokens(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] =get_tokens(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] =collections.Counter(lowerCAmelCase_ ) & collections.Counter(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : str =sum(common.values() ) if len(lowerCAmelCase_ ) == 0 or len(lowerCAmelCase_ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 SCREAMING_SNAKE_CASE_ : int =1.0 * num_same / len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : List[str] =1.0 * num_same / len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =(2 * precision * recall) / (precision + recall) return fa def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Optional[int] ,lowerCAmelCase_ : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any ={} SCREAMING_SNAKE_CASE_ : Optional[int] ={} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE_ : List[Any] =qa['id'] SCREAMING_SNAKE_CASE_ : int =[t for t in qa['answers']['text'] if normalize_answer(lowerCAmelCase_ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE_ : str =[''] if qid not in preds: print(F"""Missing prediction for {qid}""" ) continue SCREAMING_SNAKE_CASE_ : Optional[Any] =preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE_ : Any =max(compute_exact(lowerCAmelCase_ ,lowerCAmelCase_ ) for a in gold_answers ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =max(compute_fa(lowerCAmelCase_ ,lowerCAmelCase_ ) for a in gold_answers ) return exact_scores, fa_scores def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ,lowerCAmelCase_ : int ,lowerCAmelCase_ : Optional[int] ,lowerCAmelCase_ : int ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] ={} for qid, s in scores.items(): SCREAMING_SNAKE_CASE_ : Union[str, Any] =na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE_ : Optional[Any] =float(not qid_to_has_ans[qid] ) else: SCREAMING_SNAKE_CASE_ : Dict =s return new_scores def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Any ,lowerCAmelCase_ : str ,lowerCAmelCase_ : int=None ) -> Tuple: """simple docstring""" if not qid_list: SCREAMING_SNAKE_CASE_ : int =len(lowerCAmelCase_ ) return collections.OrderedDict( [ ('exact', 100.0 * sum(exact_scores.values() ) / total), ('f1', 100.0 * sum(fa_scores.values() ) / total), ('total', total), ] ) else: SCREAMING_SNAKE_CASE_ : Dict =len(lowerCAmelCase_ ) return collections.OrderedDict( [ ('exact', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('f1', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('total', total), ] ) def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Dict ,lowerCAmelCase_ : Any ,lowerCAmelCase_ : int ) -> Dict: """simple docstring""" for k in new_eval: SCREAMING_SNAKE_CASE_ : Dict =new_eval[k] def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : Dict ,lowerCAmelCase_ : Optional[Any] ,lowerCAmelCase_ : Any ) -> str: """simple docstring""" plt.step(lowerCAmelCase_ ,lowerCAmelCase_ ,color='b' ,alpha=0.2 ,where='post' ) plt.fill_between(lowerCAmelCase_ ,lowerCAmelCase_ ,step='post' ,alpha=0.2 ,color='b' ) plt.xlabel('Recall' ) plt.ylabel('Precision' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(lowerCAmelCase_ ) plt.savefig(lowerCAmelCase_ ) plt.clf() def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : List[Any] ,lowerCAmelCase_ : int ,lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : Any ,lowerCAmelCase_ : Tuple=None ,lowerCAmelCase_ : Tuple=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str =sorted(lowerCAmelCase_ ,key=lambda lowerCAmelCase_ : na_probs[k] ) SCREAMING_SNAKE_CASE_ : Optional[int] =0.0 SCREAMING_SNAKE_CASE_ : Tuple =1.0 SCREAMING_SNAKE_CASE_ : Dict =0.0 SCREAMING_SNAKE_CASE_ : Dict =[1.0] SCREAMING_SNAKE_CASE_ : str =[0.0] SCREAMING_SNAKE_CASE_ : Union[str, Any] =0.0 for i, qid in enumerate(lowerCAmelCase_ ): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE_ : List[str] =true_pos / float(i + 1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =true_pos / float(lowerCAmelCase_ ) if i == len(lowerCAmelCase_ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(lowerCAmelCase_ ) recalls.append(lowerCAmelCase_ ) if out_image: plot_pr_curve(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) return {"ap": 100.0 * avg_prec} def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : List[Any] ,lowerCAmelCase_ : List[str] ,lowerCAmelCase_ : Tuple ,lowerCAmelCase_ : str ,lowerCAmelCase_ : int ,lowerCAmelCase_ : Dict ) -> Any: """simple docstring""" if out_image_dir and not os.path.exists(lowerCAmelCase_ ): os.makedirs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : List[str] =sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return SCREAMING_SNAKE_CASE_ : List[str] =make_precision_recall_eval( lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,out_image=os.path.join(lowerCAmelCase_ ,'pr_exact.png' ) ,title='Precision-Recall curve for Exact Match score' ,) SCREAMING_SNAKE_CASE_ : int =make_precision_recall_eval( lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,out_image=os.path.join(lowerCAmelCase_ ,'pr_f1.png' ) ,title='Precision-Recall curve for F1 score' ,) SCREAMING_SNAKE_CASE_ : str ={k: float(lowerCAmelCase_ ) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE_ : List[Any] =make_precision_recall_eval( lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,out_image=os.path.join(lowerCAmelCase_ ,'pr_oracle.png' ) ,title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' ,) merge_eval(lowerCAmelCase_ ,lowerCAmelCase_ ,'pr_exact' ) merge_eval(lowerCAmelCase_ ,lowerCAmelCase_ ,'pr_f1' ) merge_eval(lowerCAmelCase_ ,lowerCAmelCase_ ,'pr_oracle' ) def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Any ,lowerCAmelCase_ : Tuple ,lowerCAmelCase_ : Optional[int] ,lowerCAmelCase_ : Optional[Any] ) -> List[str]: """simple docstring""" if not qid_list: return SCREAMING_SNAKE_CASE_ : List[str] =[na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE_ : Optional[int] =np.ones_like(lowerCAmelCase_ ) / float(len(lowerCAmelCase_ ) ) plt.hist(lowerCAmelCase_ ,weights=lowerCAmelCase_ ,bins=20 ,range=(0.0, 1.0) ) plt.xlabel('Model probability of no-answer' ) plt.ylabel('Proportion of dataset' ) plt.title(F"""Histogram of no-answer probability: {name}""" ) plt.savefig(os.path.join(lowerCAmelCase_ ,F"""na_prob_hist_{name}.png""" ) ) plt.clf() def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Dict ,lowerCAmelCase_ : Tuple ,lowerCAmelCase_ : Dict ,lowerCAmelCase_ : Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] =sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) SCREAMING_SNAKE_CASE_ : Dict =num_no_ans SCREAMING_SNAKE_CASE_ : int =cur_score SCREAMING_SNAKE_CASE_ : int =0.0 SCREAMING_SNAKE_CASE_ : Optional[Any] =sorted(lowerCAmelCase_ ,key=lambda lowerCAmelCase_ : na_probs[k] ) for i, qid in enumerate(lowerCAmelCase_ ): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE_ : List[Any] =scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE_ : int =-1 else: SCREAMING_SNAKE_CASE_ : Optional[int] =0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE_ : Tuple =cur_score SCREAMING_SNAKE_CASE_ : Optional[Any] =na_probs[qid] return 100.0 * best_score / len(lowerCAmelCase_ ), best_thresh def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : int ,lowerCAmelCase_ : Dict ,lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : Tuple ,lowerCAmelCase_ : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str =find_best_thresh(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] =find_best_thresh(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Any =best_exact SCREAMING_SNAKE_CASE_ : Dict =exact_thresh SCREAMING_SNAKE_CASE_ : Tuple =best_fa SCREAMING_SNAKE_CASE_ : Any =fa_thresh def SCREAMING_SNAKE_CASE__ ( ) -> List[str]: """simple docstring""" with open(OPTS.data_file ) as f: SCREAMING_SNAKE_CASE_ : Optional[Any] =json.load(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Any =dataset_json['data'] with open(OPTS.pred_file ) as f: SCREAMING_SNAKE_CASE_ : Any =json.load(lowerCAmelCase_ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: SCREAMING_SNAKE_CASE_ : Optional[int] =json.load(lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] ={k: 0.0 for k in preds} SCREAMING_SNAKE_CASE_ : str =make_qid_to_has_ans(lowerCAmelCase_ ) # maps qid to True/False SCREAMING_SNAKE_CASE_ : str =[k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE_ : str =[k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any =get_raw_scores(lowerCAmelCase_ ,lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =apply_no_ans_threshold(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,OPTS.na_prob_thresh ) SCREAMING_SNAKE_CASE_ : Dict =apply_no_ans_threshold(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,OPTS.na_prob_thresh ) SCREAMING_SNAKE_CASE_ : List[Any] =make_eval_dict(lowerCAmelCase_ ,lowerCAmelCase_ ) if has_ans_qids: SCREAMING_SNAKE_CASE_ : List[Any] =make_eval_dict(lowerCAmelCase_ ,lowerCAmelCase_ ,qid_list=lowerCAmelCase_ ) merge_eval(lowerCAmelCase_ ,lowerCAmelCase_ ,'HasAns' ) if no_ans_qids: SCREAMING_SNAKE_CASE_ : str =make_eval_dict(lowerCAmelCase_ ,lowerCAmelCase_ ,qid_list=lowerCAmelCase_ ) merge_eval(lowerCAmelCase_ ,lowerCAmelCase_ ,'NoAns' ) if OPTS.na_prob_file: find_all_best_thresh(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,OPTS.out_image_dir ) histogram_na_prob(lowerCAmelCase_ ,lowerCAmelCase_ ,OPTS.out_image_dir ,'hasAns' ) histogram_na_prob(lowerCAmelCase_ ,lowerCAmelCase_ ,OPTS.out_image_dir ,'noAns' ) if OPTS.out_file: with open(OPTS.out_file ,'w' ) as f: json.dump(lowerCAmelCase_ ,lowerCAmelCase_ ) else: print(json.dumps(lowerCAmelCase_ ,indent=2 ) ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
220
1
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=13 , SCREAMING_SNAKE_CASE__ : Any=30 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Any=3 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : List[Any]=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : int=37 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : int=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : int=3 , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = vocab_size UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = is_training UpperCamelCase = use_labels 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 = type_sequence_label_size UpperCamelCase = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase = (image_size // patch_size) ** 2 UpperCamelCase = num_patches + 1 def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): """simple docstring""" UpperCamelCase = FlaxBeitModel(config=SCREAMING_SNAKE_CASE__ ) UpperCamelCase = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): """simple docstring""" UpperCamelCase = FlaxBeitForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__ ) UpperCamelCase = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.type_sequence_label_size UpperCamelCase = FlaxBeitForImageClassification(config=SCREAMING_SNAKE_CASE__ ) UpperCamelCase = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase = 1 UpperCamelCase = FlaxBeitForImageClassification(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase = model(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) = config_and_inputs UpperCamelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class _lowerCAmelCase ( __magic_name__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int =( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def __lowerCAmelCase ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = FlaxBeitModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def __lowerCAmelCase ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase = model_class(SCREAMING_SNAKE_CASE__ ) @jax.jit def model_jitted(SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : int ): return model(pixel_values=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with self.subTest('JIT Enabled' ): UpperCamelCase = model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCamelCase = model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def __lowerCAmelCase ( self : Optional[int] ): """simple docstring""" for model_class_name in self.all_model_classes: UpperCamelCase = model_class_name.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase = model(np.ones((1, 3, 2_24, 2_24) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( ) -> Optional[Any]: UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @cached_property def __lowerCAmelCase ( self : int ): """simple docstring""" return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def __lowerCAmelCase ( self : Optional[int] ): """simple docstring""" UpperCamelCase = FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ).pixel_values # prepare bool_masked_pos UpperCamelCase = np.ones((1, 1_96) , dtype=SCREAMING_SNAKE_CASE__ ) # forward pass UpperCamelCase = model(pixel_values=SCREAMING_SNAKE_CASE__ , bool_masked_pos=SCREAMING_SNAKE_CASE__ ) UpperCamelCase = outputs.logits # verify the logits UpperCamelCase = (1, 1_96, 81_92) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE__ ) UpperCamelCase = np.array( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-2 ) ) @slow def __lowerCAmelCase ( self : Optional[int] ): """simple docstring""" UpperCamelCase = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) # forward pass UpperCamelCase = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase = outputs.logits # verify the logits UpperCamelCase = (1, 10_00) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE__ ) UpperCamelCase = np.array([-1.2385, -1.0987, -1.0108] ) self.assertTrue(np.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) UpperCamelCase = 2_81 self.assertEqual(logits.argmax(-1 ).item() , SCREAMING_SNAKE_CASE__ ) @slow def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) # forward pass UpperCamelCase = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase = outputs.logits # verify the logits UpperCamelCase = (1, 2_18_41) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE__ ) UpperCamelCase = np.array([1.6881, -0.2787, 0.5901] ) self.assertTrue(np.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) UpperCamelCase = 23_96 self.assertEqual(logits.argmax(-1 ).item() , SCREAMING_SNAKE_CASE__ )
718
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig _snake_case = logging.get_logger(__name__) class _lowerCAmelCase : """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int ): """simple docstring""" UpperCamelCase = question_encoder UpperCamelCase = generator UpperCamelCase = self.question_encoder def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Dict ): """simple docstring""" if os.path.isfile(SCREAMING_SNAKE_CASE__ ): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) UpperCamelCase = os.path.join(SCREAMING_SNAKE_CASE__ , 'question_encoder_tokenizer' ) UpperCamelCase = os.path.join(SCREAMING_SNAKE_CASE__ , 'generator_tokenizer' ) self.question_encoder.save_pretrained(SCREAMING_SNAKE_CASE__ ) self.generator.save_pretrained(SCREAMING_SNAKE_CASE__ ) @classmethod def __lowerCAmelCase ( cls : Any , SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : Dict ): """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer UpperCamelCase = kwargs.pop('config' , SCREAMING_SNAKE_CASE__ ) if config is None: UpperCamelCase = RagConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.question_encoder , subfolder='question_encoder_tokenizer' ) UpperCamelCase = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.generator , subfolder='generator_tokenizer' ) return cls(question_encoder=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) def __call__( self : Tuple , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ): """simple docstring""" return self.current_tokenizer(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : List[str] ): """simple docstring""" return self.generator.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Optional[Any] ): """simple docstring""" return self.generator.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): """simple docstring""" UpperCamelCase = self.question_encoder def __lowerCAmelCase ( self : str ): """simple docstring""" UpperCamelCase = self.generator def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[List[str]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "longest" , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ): """simple docstring""" warnings.warn( '`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ' 'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ' 'context manager to prepare your targets. See the documentation of your specific tokenizer for more ' 'details' , SCREAMING_SNAKE_CASE__ , ) if max_length is None: UpperCamelCase = self.current_tokenizer.model_max_length UpperCamelCase = self( SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: UpperCamelCase = self.current_tokenizer.model_max_length UpperCamelCase = self( text_target=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) UpperCamelCase = labels['input_ids'] return model_inputs
170
0
"""simple docstring""" import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def a ( __UpperCAmelCase : Any , __UpperCAmelCase : Tuple ) -> Any: __magic_name__: Union[str, Any] = old_name if "patch_embed" in old_name: __magic_name__, __magic_name__, __magic_name__: List[str] = old_name.split(""".""" ) if layer == "0": __magic_name__: Optional[int] = old_name.replace("""0""" , """convolution1""" ) elif layer == "1": __magic_name__: str = old_name.replace("""1""" , """batchnorm_before""" ) elif layer == "3": __magic_name__: Dict = old_name.replace("""3""" , """convolution2""" ) else: __magic_name__: Dict = old_name.replace("""4""" , """batchnorm_after""" ) if "network" in old_name and re.search(R"""\d\.\d""" , __UpperCAmelCase ): __magic_name__: int = R"""\b\d{2}\b""" if bool(re.search(__UpperCAmelCase , __UpperCAmelCase ) ): __magic_name__: Tuple = re.search(R"""\d\.\d\d.""" , __UpperCAmelCase ).group() else: __magic_name__: int = re.search(R"""\d\.\d.""" , __UpperCAmelCase ).group() if int(match[0] ) < 6: __magic_name__: List[Any] = old_name.replace(__UpperCAmelCase , """""" ) __magic_name__: str = trimmed_name.replace("""network""" , match[0] + """.meta4D_layers.blocks.""" + match[2:-1] ) __magic_name__: Optional[Any] = """intermediate_stages.""" + trimmed_name else: __magic_name__: Any = old_name.replace(__UpperCAmelCase , """""" ) if int(match[2] ) < num_meta4D_last_stage: __magic_name__: Dict = trimmed_name.replace("""network""" , """meta4D_layers.blocks.""" + match[2] ) else: __magic_name__: Union[str, Any] = str(int(match[2] ) - num_meta4D_last_stage ) __magic_name__: Union[str, Any] = trimmed_name.replace("""network""" , """meta3D_layers.blocks.""" + layer_index ) if "norm1" in old_name: __magic_name__: Optional[int] = trimmed_name.replace("""norm1""" , """layernorm1""" ) elif "norm2" in old_name: __magic_name__: Optional[Any] = trimmed_name.replace("""norm2""" , """layernorm2""" ) elif "fc1" in old_name: __magic_name__: Any = trimmed_name.replace("""fc1""" , """linear_in""" ) elif "fc2" in old_name: __magic_name__: int = trimmed_name.replace("""fc2""" , """linear_out""" ) __magic_name__: List[Any] = """last_stage.""" + trimmed_name elif "network" in old_name and re.search(R""".\d.""" , __UpperCAmelCase ): __magic_name__: Optional[int] = old_name.replace("""network""" , """intermediate_stages""" ) if "fc" in new_name: __magic_name__: str = new_name.replace("""fc""" , """convolution""" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): __magic_name__: Optional[int] = new_name.replace("""norm1""" , """batchnorm_before""" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): __magic_name__: List[Any] = new_name.replace("""norm2""" , """batchnorm_after""" ) if "proj" in new_name: __magic_name__: Optional[int] = new_name.replace("""proj""" , """projection""" ) if "dist_head" in new_name: __magic_name__: int = new_name.replace("""dist_head""" , """distillation_classifier""" ) elif "head" in new_name: __magic_name__: Dict = new_name.replace("""head""" , """classifier""" ) elif "patch_embed" in new_name: __magic_name__: List[str] = """efficientformer.""" + new_name elif new_name == "norm.weight" or new_name == "norm.bias": __magic_name__: Tuple = new_name.replace("""norm""" , """layernorm""" ) __magic_name__: Dict = """efficientformer.""" + new_name else: __magic_name__: Union[str, Any] = """efficientformer.encoder.""" + new_name return new_name def a ( __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] ) -> Optional[Any]: for key in checkpoint.copy().keys(): __magic_name__: List[str] = checkpoint.pop(__UpperCAmelCase ) __magic_name__: Union[str, Any] = val return checkpoint def a ( ) -> Dict: __magic_name__: Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" __magic_name__: List[Any] = Image.open(requests.get(__UpperCAmelCase , stream=__UpperCAmelCase ).raw ) return image def a ( __UpperCAmelCase : Path , __UpperCAmelCase : Path , __UpperCAmelCase : Path , __UpperCAmelCase : bool ) -> Any: __magic_name__: Union[str, Any] = torch.load(__UpperCAmelCase , map_location="""cpu""" )["""model"""] __magic_name__: List[Any] = EfficientFormerConfig.from_json_file(__UpperCAmelCase ) __magic_name__: Any = EfficientFormerForImageClassificationWithTeacher(__UpperCAmelCase ) __magic_name__: Dict = """_""".join(checkpoint_path.split("""/""" )[-1].split(""".""" )[0].split("""_""" )[:-1] ) __magic_name__: int = config.depths[-1] - config.num_metaad_blocks + 1 __magic_name__: int = convert_torch_checkpoint(__UpperCAmelCase , __UpperCAmelCase ) model.load_state_dict(__UpperCAmelCase ) model.eval() __magic_name__: Optional[Any] = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } # prepare image __magic_name__: Any = prepare_img() __magic_name__: List[Any] = 2_5_6 __magic_name__: Optional[int] = 2_2_4 __magic_name__: List[str] = EfficientFormerImageProcessor( size={"""shortest_edge""": image_size} , crop_size={"""height""": crop_size, """width""": crop_size} , resample=pillow_resamplings["""bicubic"""] , ) __magic_name__: int = processor(images=__UpperCAmelCase , return_tensors="""pt""" ).pixel_values # original processing pipeline __magic_name__: Optional[int] = Compose( [ Resize(__UpperCAmelCase , interpolation=pillow_resamplings["""bicubic"""] ), CenterCrop(__UpperCAmelCase ), ToTensor(), Normalize(__UpperCAmelCase , __UpperCAmelCase ), ] ) __magic_name__: List[str] = image_transforms(__UpperCAmelCase ).unsqueeze(0 ) assert torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) __magic_name__: Optional[Any] = model(__UpperCAmelCase ) __magic_name__: Any = outputs.logits __magic_name__: Any = (1, 1_0_0_0) if "l1" in model_name: __magic_name__: List[str] = torch.Tensor( [-0.13_12, 0.43_53, -1.04_99, -0.51_24, 0.41_83, -0.67_93, -1.37_77, -0.08_93, -0.73_58, -2.43_28] ) assert torch.allclose(logits[0, :1_0] , __UpperCAmelCase , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: __magic_name__: List[Any] = torch.Tensor( [-1.31_50, -1.54_56, -1.25_56, -0.84_96, -0.71_27, -0.78_97, -0.97_28, -0.30_52, 0.37_51, -0.31_27] ) assert torch.allclose(logits[0, :1_0] , __UpperCAmelCase , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: __magic_name__: Any = torch.Tensor( [-1.02_83, -1.41_31, -0.56_44, -1.31_15, -0.57_85, -1.20_49, -0.75_28, 0.19_92, -0.38_22, -0.08_78] ) assert logits.shape == expected_shape else: raise ValueError( f'Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7' ) # Save Checkpoints Path(__UpperCAmelCase ).mkdir(exist_ok=__UpperCAmelCase ) model.save_pretrained(__UpperCAmelCase ) print(f'Checkpoint successfuly converted. Model saved at {pytorch_dump_path}' ) processor.save_pretrained(__UpperCAmelCase ) print(f'Processor successfuly saved at {pytorch_dump_path}' ) if push_to_hub: print("""Pushing model to the hub...""" ) model.push_to_hub( repo_id=f'Bearnardd/{pytorch_dump_path}' , commit_message="""Add model""" , use_temp_dir=__UpperCAmelCase , ) processor.push_to_hub( repo_id=f'Bearnardd/{pytorch_dump_path}' , commit_message="""Add image processor""" , use_temp_dir=__UpperCAmelCase , ) if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to EfficientFormer pytorch checkpoint.', ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for EfficientFormer model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) parser.set_defaults(push_to_hub=True) __lowerCamelCase = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
96
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask __magic_name__ =logging.getLogger(__name__) class _A ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : Optional[Any] ="token-classification" def __init__(self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' if type(SCREAMING_SNAKE_CASE_ ) == dict: UpperCamelCase__ = Namespace(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = import_module('''tasks''' ) try: UpperCamelCase__ = getattr(SCREAMING_SNAKE_CASE_ , hparams.task_type ) UpperCamelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " F"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) UpperCamelCase__ = self.token_classification_task.get_labels(hparams.labels ) UpperCamelCase__ = CrossEntropyLoss().ignore_index super().__init__(SCREAMING_SNAKE_CASE_ , len(self.labels ) , self.mode ) def _a (self , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' return self.model(**SCREAMING_SNAKE_CASE_ ) def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' UpperCamelCase__ = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]} if self.config.model_type != "distilbert": UpperCamelCase__ = ( batch[2] if self.config.model_type in ['''bert''', '''xlnet'''] else None ) # XLM and RoBERTa don"t use token_type_ids UpperCamelCase__ = self(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def _a (self ) -> int: '''simple docstring''' UpperCamelCase__ = self.hparams for mode in ["train", "dev", "test"]: UpperCamelCase__ = self._feature_file(SCREAMING_SNAKE_CASE_ ) if os.path.exists(SCREAMING_SNAKE_CASE_ ) and not args.overwrite_cache: logger.info('''Loading features from cached file %s''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.load(SCREAMING_SNAKE_CASE_ ) else: logger.info('''Creating features from dataset file at %s''' , args.data_dir ) UpperCamelCase__ = self.token_classification_task.read_examples_from_file(args.data_dir , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE_ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ['''xlnet'''] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ['''xlnet'''] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE_ , pad_on_left=bool(self.config.model_type in ['''xlnet'''] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info('''Saving features into cached file %s''' , SCREAMING_SNAKE_CASE_ ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False ) -> DataLoader: '''simple docstring''' UpperCamelCase__ = self._feature_file(SCREAMING_SNAKE_CASE_ ) logger.info('''Loading features from cached file %s''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.load(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) UpperCamelCase__ = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: UpperCamelCase__ = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: UpperCamelCase__ = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) UpperCamelCase__ = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , batch_size=SCREAMING_SNAKE_CASE_ ) def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' """Compute validation""" "" UpperCamelCase__ = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]} if self.config.model_type != "distilbert": UpperCamelCase__ = ( batch[2] if self.config.model_type in ['''bert''', '''xlnet'''] else None ) # XLM and RoBERTa don"t use token_type_ids UpperCamelCase__ = self(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs[:2] UpperCamelCase__ = logits.detach().cpu().numpy() UpperCamelCase__ = inputs['''labels'''].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _a (self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = torch.stack([x['''val_loss'''] for x in outputs] ).mean() UpperCamelCase__ = np.concatenate([x['''pred'''] for x in outputs] , axis=0 ) UpperCamelCase__ = np.argmax(SCREAMING_SNAKE_CASE_ , axis=2 ) UpperCamelCase__ = np.concatenate([x['''target'''] for x in outputs] , axis=0 ) UpperCamelCase__ = dict(enumerate(self.labels ) ) UpperCamelCase__ = [[] for _ in range(out_label_ids.shape[0] )] UpperCamelCase__ = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) UpperCamelCase__ = { '''val_loss''': val_loss_mean, '''accuracy_score''': accuracy_score(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), '''precision''': precision_score(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), '''recall''': recall_score(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), '''f1''': fa_score(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), } UpperCamelCase__ = dict(results.items() ) UpperCamelCase__ = results return ret, preds_list, out_label_list def _a (self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._eval_end(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ret['''log'''] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _a (self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._eval_end(SCREAMING_SNAKE_CASE_ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 UpperCamelCase__ = ret['''log'''] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _a (SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' BaseTransformer.add_model_specific_args(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) parser.add_argument( '''--task_type''' , default='''NER''' , type=SCREAMING_SNAKE_CASE_ , help='''Task type to fine tune in training (e.g. NER, POS, etc)''' ) parser.add_argument( '''--max_seq_length''' , default=128 , type=SCREAMING_SNAKE_CASE_ , help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) , ) parser.add_argument( '''--labels''' , default='''''' , type=SCREAMING_SNAKE_CASE_ , help='''Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.''' , ) parser.add_argument( '''--gpus''' , default=0 , type=SCREAMING_SNAKE_CASE_ , help='''The number of GPUs allocated for this, it is by default 0 meaning none''' , ) parser.add_argument( '''--overwrite_cache''' , action='''store_true''' , help='''Overwrite the cached training and evaluation sets''' ) return parser if __name__ == "__main__": __magic_name__ =argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) __magic_name__ =NERTransformer.add_model_specific_args(parser, os.getcwd()) __magic_name__ =parser.parse_args() __magic_name__ =NERTransformer(args) __magic_name__ =generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 __magic_name__ =sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True)) __magic_name__ =model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
415
0
def _lowerCAmelCase ( _lowerCAmelCase ) -> int: '''simple docstring''' __snake_case = abs(_lowerCAmelCase ) __snake_case = 0 while n > 0: res += n % 10 n //= 10 return res def _lowerCAmelCase ( _lowerCAmelCase ) -> int: '''simple docstring''' __snake_case = abs(_lowerCAmelCase ) return n if n < 10 else n % 10 + sum_of_digits(n // 10 ) def _lowerCAmelCase ( _lowerCAmelCase ) -> int: '''simple docstring''' return sum(int(_lowerCAmelCase ) for c in str(abs(_lowerCAmelCase ) ) ) def _lowerCAmelCase ( ) -> None: '''simple docstring''' from collections.abc import Callable from timeit import timeit def benchmark_a_function(_lowerCAmelCase , _lowerCAmelCase ) -> None: __snake_case = F'''{func.__name__}({value})''' __snake_case = timeit(F'''__main__.{call}''' , setup="import __main__" ) print(F'''{call:56} = {func(_lowerCAmelCase )} -- {timing:.4f} seconds''' ) for value in (26_2144, 1125_8999_0684_2624, 126_7650_6002_2822_9401_4967_0320_5376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(_lowerCAmelCase , _lowerCAmelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
715
class UpperCamelCase: def __init__( self : Any ) -> Any: '''simple docstring''' __snake_case = 0 __snake_case = 0 __snake_case = {} def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE : Optional[int] ) -> Optional[Any]: '''simple docstring''' if vertex not in self.adjacency: __snake_case = {} self.num_vertices += 1 def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : str ) -> Optional[Any]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return __snake_case = weight __snake_case = weight def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Tuple: '''simple docstring''' __snake_case = self.get_edges() for edge in edges: __snake_case , __snake_case , __snake_case = edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): __snake_case = list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: __snake_case = edges[i][2] + 1 for edge in edges: __snake_case , __snake_case , __snake_case = edge __snake_case = weight __snake_case = weight def __str__( self : Tuple ) -> List[Any]: '''simple docstring''' __snake_case = "" for tail in self.adjacency: for head in self.adjacency[tail]: __snake_case = self.adjacency[head][tail] string += f'''{head} -> {tail} == {weight}\n''' return string.rstrip("\n" ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: '''simple docstring''' __snake_case = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : List[Any]=None ) -> int: '''simple docstring''' __snake_case = Graph() if vertices is None: __snake_case = [] if edges is None: __snake_case = [] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class UpperCamelCase: def __init__( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case = {} __snake_case = {} def __len__( self : List[str] ) -> Dict: '''simple docstring''' return len(self.parent ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE : int ) -> List[str]: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) __snake_case = item __snake_case = 0 return item def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] ) -> Any: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: __snake_case = self.find(self.parent[item] ) return self.parent[item] def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case = self.find(SCREAMING_SNAKE_CASE ) __snake_case = self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: __snake_case = roota return roota if self.rank[roota] < self.rank[roota]: __snake_case = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 __snake_case = roota return roota return None @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE : str ) -> Any: '''simple docstring''' __snake_case = graph.num_vertices __snake_case = Graph.UnionFind() __snake_case = [] while num_components > 1: __snake_case = {} for vertex in graph.get_vertices(): __snake_case = -1 __snake_case = graph.get_edges() for edge in edges: __snake_case , __snake_case , __snake_case = edge edges.remove((tail, head, weight) ) for edge in edges: __snake_case , __snake_case , __snake_case = edge __snake_case = union_find.find(SCREAMING_SNAKE_CASE ) __snake_case = union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __snake_case = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __snake_case = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: __snake_case , __snake_case , __snake_case = cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) __snake_case = num_components - 1 __snake_case = Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
473
0
import re from filelock import FileLock try: import nltk lowerCAmelCase_ = True except (ImportError, ModuleNotFoundError): lowerCAmelCase_ = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): re.sub('''<n>''' , '''''' , SCREAMING_SNAKE_CASE__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE__ ) )
39
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer snake_case : List[Any] = logging.get_logger(__name__) snake_case : Optional[int] = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} snake_case : Union[str, Any] = { '''vocab_file''': { '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/vocab.json''', '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/vocab.json''', '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json''', '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/vocab.json''', '''roberta-base-openai-detector''': '''https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json''', '''roberta-large-openai-detector''': ( '''https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json''' ), }, '''merges_file''': { '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/merges.txt''', '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/merges.txt''', '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt''', '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/merges.txt''', '''roberta-base-openai-detector''': '''https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt''', '''roberta-large-openai-detector''': ( '''https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt''' ), }, '''tokenizer_file''': { '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/tokenizer.json''', '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/tokenizer.json''', '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json''', '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json''', '''roberta-base-openai-detector''': ( '''https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json''' ), '''roberta-large-openai-detector''': ( '''https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json''' ), }, } snake_case : Optional[int] = { '''roberta-base''': 5_12, '''roberta-large''': 5_12, '''roberta-large-mnli''': 5_12, '''distilroberta-base''': 5_12, '''roberta-base-openai-detector''': 5_12, '''roberta-large-openai-detector''': 5_12, } class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['input_ids', 'attention_mask'] SCREAMING_SNAKE_CASE__ = RobertaTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="replace" , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase=False , _lowerCamelCase=True , **_lowerCamelCase , ): super().__init__( _lowerCamelCase , _lowerCamelCase , tokenizer_file=_lowerCamelCase , errors=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , add_prefix_space=_lowerCamelCase , trim_offsets=_lowerCamelCase , **_lowerCamelCase , ) a :List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , _lowerCamelCase ) != add_prefix_space: a :Optional[int] = getattr(_lowerCamelCase , pre_tok_state.pop('''type''' ) ) a :Union[str, Any] = add_prefix_space a :Dict = pre_tok_class(**_lowerCamelCase ) a :Union[str, Any] = add_prefix_space a :List[Any] = '''post_processor''' a :List[str] = getattr(self.backend_tokenizer , _lowerCamelCase , _lowerCamelCase ) if tokenizer_component_instance: a :Optional[Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a :Optional[int] = tuple(state['''sep'''] ) if "cls" in state: a :Union[str, Any] = tuple(state['''cls'''] ) a :Optional[int] = False if state.get('''add_prefix_space''' , _lowerCamelCase ) != add_prefix_space: a :int = add_prefix_space a :Union[str, Any] = True if state.get('''trim_offsets''' , _lowerCamelCase ) != trim_offsets: a :int = trim_offsets a :List[str] = True if changes_to_apply: a :Union[str, Any] = getattr(_lowerCamelCase , state.pop('''type''' ) ) a :str = component_class(**_lowerCamelCase ) setattr(self.backend_tokenizer , _lowerCamelCase , _lowerCamelCase ) @property def SCREAMING_SNAKE_CASE__ ( self ): if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): a :Union[str, Any] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else value a :int = value def SCREAMING_SNAKE_CASE__ ( self , *_lowerCamelCase , **_lowerCamelCase ): a :Union[str, Any] = kwargs.get('''is_split_into_words''' , _lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , *_lowerCamelCase , **_lowerCamelCase ): a :Any = kwargs.get('''is_split_into_words''' , _lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ): a :Any = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase=None ): a :Union[str, Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ): a :Dict = [self.sep_token_id] a :int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
445
0
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A__ ( __A ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A__ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" _lowerCamelCase : List[str] = [1, 2, 3] with pytest.raises(__A ): with parallel_backend("""unsupported backend""" ): map_nested(__A , __A , num_proc=2 ) with pytest.raises(__A ): with parallel_backend("""unsupported backend""" ): map_nested(__A , __A , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" , [2, -1] ) def A__ ( __A ): '''simple docstring''' _lowerCamelCase : Optional[Any] = [1, 2] _lowerCamelCase : str = {"""a""": 1, """b""": 2} _lowerCamelCase : Dict = {"""a""": [1, 2], """b""": [3, 4]} _lowerCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} _lowerCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} _lowerCamelCase : Dict = [2, 3] _lowerCamelCase : str = {"""a""": 2, """b""": 3} _lowerCamelCase : Tuple = {"""a""": [2, 3], """b""": [4, 5]} _lowerCamelCase : Union[str, Any] = {"""a""": {"""1""": 2}, """b""": 3} _lowerCamelCase : List[Any] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa
15
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase : Tuple =logging.get_logger(__name__) class __snake_case ( __lowerCAmelCase ): '''simple docstring''' _snake_case = ['pixel_values'] def __init__( self : Optional[Any] , _UpperCamelCase : bool = True , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : PILImageResampling = PIL.Image.BICUBIC , _UpperCamelCase : bool = True , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : Union[int, float] = 1 / 255 , _UpperCamelCase : bool = True , _UpperCamelCase : bool = True , _UpperCamelCase : Optional[Union[float, List[float]]] = None , _UpperCamelCase : Optional[Union[float, List[float]]] = None , **_UpperCamelCase : str , ) ->None: """simple docstring""" super().__init__(**_UpperCamelCase) _lowerCamelCase : Tuple = size if size is not None else {"""height""": 256, """width""": 256} _lowerCamelCase : Optional[Any] = get_size_dict(_UpperCamelCase) _lowerCamelCase : Any = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} _lowerCamelCase : Any = get_size_dict(_UpperCamelCase , param_name="""crop_size""") _lowerCamelCase : int = do_resize _lowerCamelCase : int = size _lowerCamelCase : Optional[int] = resample _lowerCamelCase : int = do_center_crop _lowerCamelCase : Optional[Any] = crop_size _lowerCamelCase : Union[str, Any] = do_rescale _lowerCamelCase : List[str] = rescale_factor _lowerCamelCase : List[Any] = do_normalize _lowerCamelCase : Dict = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowerCamelCase : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : Any , _UpperCamelCase : np.ndarray , _UpperCamelCase : Dict[str, int] , _UpperCamelCase : PILImageResampling = PIL.Image.BICUBIC , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Union[str, Any] , ) ->np.ndarray: """simple docstring""" _lowerCamelCase : Dict = get_size_dict(_UpperCamelCase) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""") return resize( _UpperCamelCase , size=(size["""height"""], size["""width"""]) , resample=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase) def _SCREAMING_SNAKE_CASE ( self : List[str] , _UpperCamelCase : np.ndarray , _UpperCamelCase : Dict[str, int] , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : List[str] , ) ->np.ndarray: """simple docstring""" _lowerCamelCase : Union[str, Any] = get_size_dict(_UpperCamelCase) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""") return center_crop(_UpperCamelCase , size=(size["""height"""], size["""width"""]) , data_format=_UpperCamelCase , **_UpperCamelCase) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , _UpperCamelCase : np.ndarray , _UpperCamelCase : Union[int, float] , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Union[str, Any] , ) ->str: """simple docstring""" return rescale(_UpperCamelCase , scale=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase) def _SCREAMING_SNAKE_CASE ( self : List[Any] , _UpperCamelCase : np.ndarray , _UpperCamelCase : Union[float, List[float]] , _UpperCamelCase : Union[float, List[float]] , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Union[str, Any] , ) ->np.ndarray: """simple docstring""" return normalize(_UpperCamelCase , mean=_UpperCamelCase , std=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , _UpperCamelCase : ImageInput , _UpperCamelCase : bool = None , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : Tuple=None , _UpperCamelCase : bool = None , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : bool = None , _UpperCamelCase : float = None , _UpperCamelCase : bool = None , _UpperCamelCase : Optional[Union[float, List[float]]] = None , _UpperCamelCase : Optional[Union[float, List[float]]] = None , _UpperCamelCase : Optional[Union[str, TensorType]] = None , _UpperCamelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCamelCase : List[Any] , ) ->PIL.Image.Image: """simple docstring""" _lowerCamelCase : Any = do_resize if do_resize is not None else self.do_resize _lowerCamelCase : List[str] = resample if resample is not None else self.resample _lowerCamelCase : Dict = do_center_crop if do_center_crop is not None else self.do_center_crop _lowerCamelCase : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale _lowerCamelCase : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCamelCase : Dict = do_normalize if do_normalize is not None else self.do_normalize _lowerCamelCase : int = image_mean if image_mean is not None else self.image_mean _lowerCamelCase : Dict = image_std if image_std is not None else self.image_std _lowerCamelCase : Optional[Any] = size if size is not None else self.size _lowerCamelCase : Optional[int] = get_size_dict(_UpperCamelCase) _lowerCamelCase : List[str] = crop_size if crop_size is not None else self.crop_size _lowerCamelCase : Dict = get_size_dict(_UpperCamelCase , param_name="""crop_size""") _lowerCamelCase : int = make_list_of_images(_UpperCamelCase) if not valid_images(_UpperCamelCase): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""") if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""") if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""") if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""") if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""") # All transformations expect numpy arrays. _lowerCamelCase : Union[str, Any] = [to_numpy_array(_UpperCamelCase) for image in images] if do_resize: _lowerCamelCase : Any = [self.resize(image=_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase) for image in images] if do_center_crop: _lowerCamelCase : str = [self.center_crop(image=_UpperCamelCase , size=_UpperCamelCase) for image in images] if do_rescale: _lowerCamelCase : Optional[int] = [self.rescale(image=_UpperCamelCase , scale=_UpperCamelCase) for image in images] if do_normalize: _lowerCamelCase : List[str] = [self.normalize(image=_UpperCamelCase , mean=_UpperCamelCase , std=_UpperCamelCase) for image in images] _lowerCamelCase : List[str] = [to_channel_dimension_format(_UpperCamelCase , _UpperCamelCase) for image in images] _lowerCamelCase : int = {"""pixel_values""": images} return BatchFeature(data=_UpperCamelCase , tensor_type=_UpperCamelCase)
15
1