code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[int] = { """post_extract_proj""": """feature_projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def _A (__a , __a , __a , __a , __a ) -> Union[str, Any]: """simple docstring""" for attribute in key.split('''.''' ): SCREAMING_SNAKE_CASE_ : str = getattr(__a , __a ) if weight_type is not None: SCREAMING_SNAKE_CASE_ : Dict = getattr(__a , __a ).shape else: SCREAMING_SNAKE_CASE_ : List[str] = 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": SCREAMING_SNAKE_CASE_ : Dict = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE_ : Union[str, Any] = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE_ : Tuple = value elif weight_type == "bias": SCREAMING_SNAKE_CASE_ : Dict = value else: SCREAMING_SNAKE_CASE_ : Optional[Any] = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def _A (__a , __a , __a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : List[Any] = fairseq_model.state_dict() SCREAMING_SNAKE_CASE_ : Any = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE_ : Dict = False if "conv_layers" in name: load_conv_layer( __a , __a , __a , __a , hf_model.config.feat_extract_norm == '''group''' , ) SCREAMING_SNAKE_CASE_ : Any = True else: for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''sew.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: SCREAMING_SNAKE_CASE_ : Optional[int] = True if "*" in mapped_key: SCREAMING_SNAKE_CASE_ : int = name.split(__a )[0].split('''.''' )[-2] SCREAMING_SNAKE_CASE_ : Optional[int] = mapped_key.replace('''*''' , __a ) if "weight_g" in name: SCREAMING_SNAKE_CASE_ : Dict = '''weight_g''' elif "weight_v" in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''weight_v''' elif "weight" in name: SCREAMING_SNAKE_CASE_ : Tuple = '''weight''' elif "bias" in name: SCREAMING_SNAKE_CASE_ : Dict = '''bias''' else: SCREAMING_SNAKE_CASE_ : List[str] = 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 _A (__a , __a , __a , __a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = full_name.split('''conv_layers.''' )[-1] SCREAMING_SNAKE_CASE_ : str = name.split('''.''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = int(items[0] ) SCREAMING_SNAKE_CASE_ : List[str] = 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.' ) SCREAMING_SNAKE_CASE_ : Optional[int] = 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.' ) SCREAMING_SNAKE_CASE_ : Optional[int] = 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." ) SCREAMING_SNAKE_CASE_ : Tuple = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) SCREAMING_SNAKE_CASE_ : Optional[int] = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__a ) def _A (__a , __a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = SEWConfig() if is_finetuned: SCREAMING_SNAKE_CASE_ : Optional[int] = model.wav_encoder.wav_model.cfg else: SCREAMING_SNAKE_CASE_ : Optional[int] = model.cfg SCREAMING_SNAKE_CASE_ : Tuple = fs_config.conv_bias SCREAMING_SNAKE_CASE_ : Tuple = eval(fs_config.conv_feature_layers ) SCREAMING_SNAKE_CASE_ : Any = [x[0] for x in conv_layers] SCREAMING_SNAKE_CASE_ : int = [x[1] for x in conv_layers] SCREAMING_SNAKE_CASE_ : int = [x[2] for x in conv_layers] SCREAMING_SNAKE_CASE_ : List[Any] = '''gelu''' SCREAMING_SNAKE_CASE_ : List[Any] = '''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group''' SCREAMING_SNAKE_CASE_ : List[str] = 0.0 SCREAMING_SNAKE_CASE_ : Dict = fs_config.activation_fn.name SCREAMING_SNAKE_CASE_ : Optional[Any] = fs_config.encoder_embed_dim SCREAMING_SNAKE_CASE_ : List[str] = 0.02 SCREAMING_SNAKE_CASE_ : Tuple = fs_config.encoder_ffn_embed_dim SCREAMING_SNAKE_CASE_ : List[Any] = 1e-5 SCREAMING_SNAKE_CASE_ : Tuple = fs_config.encoder_layerdrop SCREAMING_SNAKE_CASE_ : Optional[int] = fs_config.encoder_attention_heads SCREAMING_SNAKE_CASE_ : Any = fs_config.conv_pos_groups SCREAMING_SNAKE_CASE_ : Tuple = fs_config.conv_pos SCREAMING_SNAKE_CASE_ : Dict = len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = fs_config.encoder_layers SCREAMING_SNAKE_CASE_ : Optional[Any] = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: SCREAMING_SNAKE_CASE_ : Optional[int] = model.cfg SCREAMING_SNAKE_CASE_ : Optional[Any] = fs_config.final_dropout SCREAMING_SNAKE_CASE_ : Dict = fs_config.layerdrop SCREAMING_SNAKE_CASE_ : Tuple = fs_config.activation_dropout SCREAMING_SNAKE_CASE_ : str = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 SCREAMING_SNAKE_CASE_ : int = fs_config.attention_dropout SCREAMING_SNAKE_CASE_ : Dict = fs_config.dropout_input SCREAMING_SNAKE_CASE_ : List[str] = fs_config.dropout SCREAMING_SNAKE_CASE_ : Any = fs_config.mask_channel_length SCREAMING_SNAKE_CASE_ : Optional[int] = fs_config.mask_channel_prob SCREAMING_SNAKE_CASE_ : str = fs_config.mask_length SCREAMING_SNAKE_CASE_ : Tuple = fs_config.mask_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''Wav2Vec2FeatureExtractor''' SCREAMING_SNAKE_CASE_ : Any = '''Wav2Vec2CTCTokenizer''' return config @torch.no_grad() def _A (__a , __a , __a=None , __a=None , __a=True ) -> str: """simple docstring""" if is_finetuned: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: SCREAMING_SNAKE_CASE_ : Tuple = SEWConfig.from_pretrained(__a ) else: SCREAMING_SNAKE_CASE_ : Dict = convert_config(model[0] , __a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model[0].eval() SCREAMING_SNAKE_CASE_ : List[str] = True if config.feat_extract_norm == '''layer''' else False SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=__a , return_attention_mask=__a , ) if is_finetuned: if dict_path: SCREAMING_SNAKE_CASE_ : str = Dictionary.load(__a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq SCREAMING_SNAKE_CASE_ : List[str] = target_dict.pad_index SCREAMING_SNAKE_CASE_ : Tuple = target_dict.bos_index SCREAMING_SNAKE_CASE_ : Any = target_dict.pad_index SCREAMING_SNAKE_CASE_ : Dict = target_dict.bos_index SCREAMING_SNAKE_CASE_ : str = target_dict.eos_index SCREAMING_SNAKE_CASE_ : str = len(target_dict.symbols ) SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.join(__a , '''vocab.json''' ) if not os.path.isdir(__a ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__a ) ) return os.makedirs(__a , exist_ok=__a ) with open(__a , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices , __a ) SCREAMING_SNAKE_CASE_ : Tuple = WavaVecaCTCTokenizer( __a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=__a , ) SCREAMING_SNAKE_CASE_ : Tuple = WavaVecaProcessor(feature_extractor=__a , tokenizer=__a ) processor.save_pretrained(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = SEWForCTC(__a ) else: SCREAMING_SNAKE_CASE_ : List[Any] = SEWModel(__a ) feature_extractor.save_pretrained(__a ) recursively_load_weights(__a , __a , __a ) hf_model.save_pretrained(__a ) if __name__ == "__main__": UpperCAmelCase_ : int = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCAmelCase_ : int = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
91
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
1
"""simple docstring""" def _A (__a , __a ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(bin(__a ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE_ : Dict = str(bin(__a ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE_ : List[str] = max(len(__a ) , len(__a ) ) return "0b" + "".join( str(int(char_a == '''1''' and char_b == '''1''' ) ) for char_a, char_b in zip(a_binary.zfill(__a ) , b_binary.zfill(__a ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
91
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''') if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''') if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
1
"""simple docstring""" import warnings from .generation import TFGenerationMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' warnings.warn( "Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will " "be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead." , UpperCAmelCase__ , )
91
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
1
"""simple docstring""" import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase_ : int = """bart""" UpperCAmelCase_ : Dict = True @st.cache(allow_output_mutation=__a ) def _A () -> Union[str, Any]: """simple docstring""" if LOAD_DENSE_INDEX: SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) SCREAMING_SNAKE_CASE_ : Dict = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = qar_model.eval() else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = (None, None) if MODEL_TYPE == "bart": SCREAMING_SNAKE_CASE_ : str = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) SCREAMING_SNAKE_CASE_ : List[Any] = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) SCREAMING_SNAKE_CASE_ : List[str] = sas_model.eval() else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=__a ) def _A () -> Optional[int]: """simple docstring""" if LOAD_DENSE_INDEX: SCREAMING_SNAKE_CASE_ : int = faiss.StandardGpuResources() SCREAMING_SNAKE_CASE_ : int = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , ) SCREAMING_SNAKE_CASE_ : str = faiss.IndexFlatIP(1_28 ) SCREAMING_SNAKE_CASE_ : Dict = faiss.index_cpu_to_gpu(__a , 1 , __a ) wikiaab_gpu_index_flat.add(__a ) # TODO fix for larger GPU else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = (None, None) SCREAMING_SNAKE_CASE_ : List[Any] = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=__a ) def _A () -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) SCREAMING_SNAKE_CASE_ : str = elia['''train_eli5'''] SCREAMING_SNAKE_CASE_ : Optional[int] = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28) ) SCREAMING_SNAKE_CASE_ : str = faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(__a ) return (elia_train, eli5_train_q_index) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = load_indexes() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Any = load_models() UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = load_train_data() def _A (__a , __a=10 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = embed_questions_for_retrieval([question] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = eli5_train_q_index.search(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = [elia_train[int(__a )] for i in I[0]] return nn_examples def _A (__a , __a="wiki40b" , __a="dense" , __a=10 ) -> str: """simple docstring""" if source == "none": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = query_qa_dense_index( __a , __a , __a , __a , __a , __a ) else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = query_es_index( __a , __a , index_name='''english_wiki40b_snippets_100w''' , n_results=__a , ) SCREAMING_SNAKE_CASE_ : str = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] SCREAMING_SNAKE_CASE_ : Optional[int] = '''question: {} context: {}'''.format(__a , __a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __a : None), } ) def _A (__a , __a , __a , __a=64 , __a=2_56 , __a=False , __a=2 , __a=0.95 , __a=0.8 ) -> Union[str, Any]: """simple docstring""" with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = qa_sas_generate( __a , __a , __a , num_answers=1 , num_beams=__a , min_len=__a , max_len=__a , do_sample=__a , temp=__a , top_p=__a , top_k=__a , max_input_length=10_24 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("""Long Form Question Answering with ELI5""") # Start sidebar UpperCAmelCase_ : Any = """<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>""" UpperCAmelCase_ : Optional[int] = """ <html> <head> <style> .img-container { padding-left: 90px; padding-right: 90px; padding-top: 50px; padding-bottom: 50px; background-color: #f0f3f9; } </style> </head> <body> <span class=\"img-container\"> <!-- Inline parent element --> %s </span> </body> </html> """ % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase_ : Any = """ This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html). First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset, a pre-processed fixed snapshot of Wikipedia. """ st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase_ : Optional[Any] = [ """Answer the question""", """View the retrieved document only""", """View the most similar ELI5 question and answer""", """Show me everything, please!""", ] UpperCAmelCase_ : Optional[Any] = st.sidebar.checkbox("""Demo options""") if demo_options: UpperCAmelCase_ : Optional[Any] = st.sidebar.selectbox( """""", action_list, index=3, ) UpperCAmelCase_ : Tuple = action_list.index(action_st) UpperCAmelCase_ : Optional[Any] = st.sidebar.selectbox( """""", ["""Show full text of passages""", """Show passage section titles"""], index=0, ) UpperCAmelCase_ : Union[str, Any] = show_type == """Show full text of passages""" else: UpperCAmelCase_ : int = 3 UpperCAmelCase_ : Optional[int] = True UpperCAmelCase_ : Optional[Any] = st.sidebar.checkbox("""Retrieval options""") if retrieval_options: UpperCAmelCase_ : Optional[Any] = """ ### Information retriever options The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs. The answer is then generated by sequence to sequence model which takes the question and retrieved document as input. """ st.sidebar.markdown(retriever_info) UpperCAmelCase_ : int = st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""]) UpperCAmelCase_ : Dict = st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""]) else: UpperCAmelCase_ : List[Any] = """wiki40b""" UpperCAmelCase_ : str = """dense""" UpperCAmelCase_ : Any = """beam""" UpperCAmelCase_ : Optional[Any] = 2 UpperCAmelCase_ : Optional[int] = 64 UpperCAmelCase_ : Any = 256 UpperCAmelCase_ : Union[str, Any] = None UpperCAmelCase_ : Any = None UpperCAmelCase_ : Any = st.sidebar.checkbox("""Generation options""") if generate_options: UpperCAmelCase_ : int = """ ### Answer generation options The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large) weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with **beam** search, or **sample** from the decoder's output probabilities. """ st.sidebar.markdown(generate_info) UpperCAmelCase_ : Optional[int] = st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""]) UpperCAmelCase_ : Optional[Any] = st.sidebar.slider( """Minimum generation length""", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase_ : Optional[int] = st.sidebar.slider( """Maximum generation length""", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase_ : Union[str, Any] = st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase_ : str = st.sidebar.slider( """Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) UpperCAmelCase_ : str = st.sidebar.slider( """Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) UpperCAmelCase_ : Union[str, Any] = None # start main text UpperCAmelCase_ : Optional[int] = [ """<MY QUESTION>""", """How do people make chocolate?""", """Why do we get a fever when we are sick?""", """How can different animals perceive different colors?""", """What is natural language processing?""", """What's the best way to treat a sunburn?""", """What exactly are vitamins ?""", """How does nuclear energy provide electricity?""", """What's the difference between viruses and bacteria?""", """Why are flutes classified as woodwinds when most of them are made out of metal ?""", """Why do people like drinking coffee even though it tastes so bad?""", """What happens when wine ages? How does it make the wine taste better?""", """If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?""", """How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?""", """How does New Zealand have so many large bird predators?""", ] UpperCAmelCase_ : Union[str, Any] = st.selectbox( """What would you like to ask? ---- select <MY QUESTION> to enter a new query""", questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase_ : Optional[int] = st.text_input("""Enter your question here:""", """""") else: UpperCAmelCase_ : int = question_s if st.button("""Show me!"""): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase_ , UpperCAmelCase_ : str = make_support(question, source=wiki_source, method="""dense""", n_results=10) UpperCAmelCase_ , UpperCAmelCase_ : int = make_support(question, source=wiki_source, method="""sparse""", n_results=10) UpperCAmelCase_ : Optional[int] = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase_ : List[Any] = support_list[:10] UpperCAmelCase_ : Tuple = """<P> """ + """ <P> """.join([res[-1] for res in support_list]) else: UpperCAmelCase_ , UpperCAmelCase_ : Any = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase_ , UpperCAmelCase_ : str = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == """sampled"""), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("""### The model generated answer is:""") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("""--- \n ### The model is drawing information from the following Wikipedia passages:""") for i, res in enumerate(support_list): UpperCAmelCase_ : Optional[int] = """https://en.wikipedia.org/wiki/{}""".format(res[0].replace(""" """, """_""")) UpperCAmelCase_ : Optional[int] = res[1].strip() if sec_titles == "": UpperCAmelCase_ : Dict = """[{}]({})""".format(res[0], wiki_url) else: UpperCAmelCase_ : str = sec_titles.split(""" & """) UpperCAmelCase_ : Dict = """ & """.join( ["""[{}]({}#{})""".format(sec.strip(), wiki_url, sec.strip().replace(""" """, """_""")) for sec in sec_list] ) st.markdown( """{0:02d} - **Article**: {1:<18} <br> _Section_: {2}""".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( """> <span style=\"font-family:arial; font-size:10pt;\">""" + res[-1] + """</span>""", unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase_ : int = find_nearest_training(question) UpperCAmelCase_ : List[Any] = nn_train_list[0] st.markdown( """--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""]) ) UpperCAmelCase_ : str = [ """{}. {}""".format(i + 1, """ \n""".join([line.strip() for line in ans.split("""\n""") if line.strip() != """"""])) for i, (ans, sc) in enumerate(zip(train_exple["""answers"""]["""text"""], train_exple["""answers"""]["""score"""])) if i == 0 or sc > 2 ] st.markdown("""##### Its answers were: \n\n {}""".format("""\n""".join(answers_st))) UpperCAmelCase_ : Dict = """ --- **Disclaimer** *The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system. Evaluating biases of such a model and ensuring factual generations are still very much open research problems. Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.* """ st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
91
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
1
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = OrderedDict() for key, value in state_dict.items(): if key.startswith('''module.encoder''' ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = key.replace('''module.encoder''' , '''glpn.encoder''' ) if key.startswith('''module.decoder''' ): SCREAMING_SNAKE_CASE_ : List[Any] = key.replace('''module.decoder''' , '''decoder.stages''' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 SCREAMING_SNAKE_CASE_ : List[Any] = key[key.find('''patch_embed''' ) + len('''patch_embed''' )] SCREAMING_SNAKE_CASE_ : Optional[int] = key.replace(f'patch_embed{idx}' , f'patch_embeddings.{int(__a )-1}' ) if "norm" in key: SCREAMING_SNAKE_CASE_ : Dict = key.replace('''norm''' , '''layer_norm''' ) if "glpn.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 SCREAMING_SNAKE_CASE_ : Optional[Any] = key[key.find('''glpn.encoder.layer_norm''' ) + len('''glpn.encoder.layer_norm''' )] SCREAMING_SNAKE_CASE_ : int = key.replace(f'layer_norm{idx}' , f'layer_norm.{int(__a )-1}' ) if "layer_norm1" in key: SCREAMING_SNAKE_CASE_ : List[str] = key.replace('''layer_norm1''' , '''layer_norm_1''' ) if "layer_norm2" in key: SCREAMING_SNAKE_CASE_ : List[str] = key.replace('''layer_norm2''' , '''layer_norm_2''' ) if "block" in key: # replace for example block1 by block.0 SCREAMING_SNAKE_CASE_ : Optional[int] = key[key.find('''block''' ) + len('''block''' )] SCREAMING_SNAKE_CASE_ : Tuple = key.replace(f'block{idx}' , f'block.{int(__a )-1}' ) if "attn.q" in key: SCREAMING_SNAKE_CASE_ : Union[str, Any] = key.replace('''attn.q''' , '''attention.self.query''' ) if "attn.proj" in key: SCREAMING_SNAKE_CASE_ : Optional[int] = key.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in key: SCREAMING_SNAKE_CASE_ : List[str] = key.replace('''attn''' , '''attention.self''' ) if "fc1" in key: SCREAMING_SNAKE_CASE_ : List[str] = key.replace('''fc1''' , '''dense1''' ) if "fc2" in key: SCREAMING_SNAKE_CASE_ : List[str] = key.replace('''fc2''' , '''dense2''' ) if "linear_pred" in key: SCREAMING_SNAKE_CASE_ : Optional[Any] = key.replace('''linear_pred''' , '''classifier''' ) if "linear_fuse" in key: SCREAMING_SNAKE_CASE_ : str = key.replace('''linear_fuse.conv''' , '''linear_fuse''' ) SCREAMING_SNAKE_CASE_ : List[str] = key.replace('''linear_fuse.bn''' , '''batch_norm''' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 SCREAMING_SNAKE_CASE_ : Tuple = key[key.find('''linear_c''' ) + len('''linear_c''' )] SCREAMING_SNAKE_CASE_ : Union[str, Any] = key.replace(f'linear_c{idx}' , f'linear_c.{int(__a )-1}' ) if "bot_conv" in key: SCREAMING_SNAKE_CASE_ : Tuple = key.replace('''bot_conv''' , '''0.convolution''' ) if "skip_conv1" in key: SCREAMING_SNAKE_CASE_ : Optional[int] = key.replace('''skip_conv1''' , '''1.convolution''' ) if "skip_conv2" in key: SCREAMING_SNAKE_CASE_ : List[Any] = key.replace('''skip_conv2''' , '''2.convolution''' ) if "fusion1" in key: SCREAMING_SNAKE_CASE_ : Tuple = key.replace('''fusion1''' , '''1.fusion''' ) if "fusion2" in key: SCREAMING_SNAKE_CASE_ : Dict = key.replace('''fusion2''' , '''2.fusion''' ) if "fusion3" in key: SCREAMING_SNAKE_CASE_ : Dict = key.replace('''fusion3''' , '''3.fusion''' ) if "fusion" in key and "conv" in key: SCREAMING_SNAKE_CASE_ : Tuple = key.replace('''conv''' , '''convolutional_layer''' ) if key.startswith('''module.last_layer_depth''' ): SCREAMING_SNAKE_CASE_ : str = key.replace('''module.last_layer_depth''' , '''head.head''' ) SCREAMING_SNAKE_CASE_ : Any = value return new_state_dict def _A (__a , __a ) -> List[str]: """simple docstring""" for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) SCREAMING_SNAKE_CASE_ : List[Any] = state_dict.pop(f'glpn.encoder.block.{i}.{j}.attention.self.kv.weight' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = state_dict.pop(f'glpn.encoder.block.{i}.{j}.attention.self.kv.bias' ) # next, add keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : str = kv_weight[ : config.hidden_sizes[i], : ] SCREAMING_SNAKE_CASE_ : str = kv_bias[: config.hidden_sizes[i]] SCREAMING_SNAKE_CASE_ : Optional[int] = kv_weight[ config.hidden_sizes[i] :, : ] SCREAMING_SNAKE_CASE_ : List[str] = kv_bias[config.hidden_sizes[i] :] def _A () -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ : List[str] = Image.open(requests.get(__a , stream=__a ).raw ) return image @torch.no_grad() def _A (__a , __a , __a=False , __a=None ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = GLPNConfig(hidden_sizes=[64, 1_28, 3_20, 5_12] , decoder_hidden_size=64 , depths=[3, 8, 27, 3] ) # load image processor (only resize + rescale) SCREAMING_SNAKE_CASE_ : str = GLPNImageProcessor() # prepare image SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : List[str] = image_processor(images=__a , return_tensors='''pt''' ).pixel_values logger.info('''Converting model...''' ) # load original state dict SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.load(__a , map_location=torch.device('''cpu''' ) ) # rename keys SCREAMING_SNAKE_CASE_ : Dict = rename_keys(__a ) # key and value matrices need special treatment read_in_k_v(__a , __a ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE_ : List[Any] = GLPNForDepthEstimation(__a ) model.load_state_dict(__a ) model.eval() # forward pass SCREAMING_SNAKE_CASE_ : List[str] = model(__a ) SCREAMING_SNAKE_CASE_ : Dict = outputs.predicted_depth # verify output if model_name is not None: if "nyu" in model_name: SCREAMING_SNAKE_CASE_ : str = torch.tensor( [[4.41_47, 4.08_73, 4.06_73], [3.78_90, 3.28_81, 3.15_25], [3.76_74, 3.54_23, 3.49_13]] ) elif "kitti" in model_name: SCREAMING_SNAKE_CASE_ : int = torch.tensor( [[3.42_91, 2.78_65, 2.51_51], [3.28_41, 2.70_21, 2.35_02], [3.11_47, 2.46_25, 2.24_81]] ) else: raise ValueError(f'Unknown model name: {model_name}' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.Size([1, 4_80, 6_40] ) assert predicted_depth.shape == expected_shape assert torch.allclose(predicted_depth[0, :3, :3] , __a , atol=1e-4 ) print('''Looks ok!''' ) # finally, push to hub if required if push_to_hub: logger.info('''Pushing model and image processor to the hub...''' ) model.push_to_hub( repo_path_or_name=Path(__a , __a ) , organization='''nielsr''' , commit_message='''Add model''' , use_temp_dir=__a , ) image_processor.push_to_hub( repo_path_or_name=Path(__a , __a ) , organization='''nielsr''' , commit_message='''Add image processor''' , use_temp_dir=__a , ) if __name__ == "__main__": UpperCAmelCase_ : Any = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, help="""Path 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""", help="""Whether to upload the model to the HuggingFace hub.""" ) parser.add_argument( """--model_name""", default="""glpn-kitti""", type=str, help="""Name of the model in case you're pushing to the hub.""", ) UpperCAmelCase_ : Optional[Any] = parser.parse_args() convert_glpn_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
91
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
1
"""simple docstring""" import math from collections.abc import Callable def _A (__a , __a , __a ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : float = xa SCREAMING_SNAKE_CASE_ : float = xa while True: if x_n == x_na or function(__a ) == function(__a ): raise ZeroDivisionError('''float division by zero, could not find root''' ) SCREAMING_SNAKE_CASE_ : float = x_na - ( function(__a ) / ((function(__a ) - function(__a )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE_ : List[str] = x_na SCREAMING_SNAKE_CASE_ : List[str] = x_na def _A (__a ) -> float: """simple docstring""" return math.pow(__a , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = { """Salesforce/blip-vqa-base""": """https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json""", """Salesforce/blip-vqa-capfit-large""": ( """https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json""" ), """Salesforce/blip-image-captioning-base""": ( """https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json""" ), """Salesforce/blip-image-captioning-large""": ( """https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json""" ), """Salesforce/blip-itm-base-coco""": """https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json""", """Salesforce/blip-itm-large-coco""": """https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json""", """Salesforce/blip-itm-base-flikr""": """https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json""", """Salesforce/blip-itm-large-flikr""": ( """https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json""" ), } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "blip_text_model" def __init__( self : Tuple , lowercase_ : str=30524 , lowercase_ : Union[str, Any]=768 , lowercase_ : Optional[Any]=768 , lowercase_ : Dict=3072 , lowercase_ : Optional[Any]=768 , lowercase_ : Any=12 , lowercase_ : Dict=8 , lowercase_ : str=512 , lowercase_ : Any="gelu" , lowercase_ : str=1e-12 , lowercase_ : List[str]=0.0 , lowercase_ : Any=0.0 , lowercase_ : List[str]=0.02 , lowercase_ : int=30522 , lowercase_ : Any=2 , lowercase_ : Optional[int]=0 , lowercase_ : Union[str, Any]=102 , lowercase_ : Optional[Any]=True , lowercase_ : str=True , **lowercase_ : Optional[Any] , ): '''simple docstring''' super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , sep_token_id=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : List[str] = vocab_size SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : List[str] = encoder_hidden_size SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : str = projection_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE_ : int = hidden_act SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_decoder SCREAMING_SNAKE_CASE_ : Optional[int] = use_cache @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] , lowercase_ : Union[str, os.PathLike] , **lowercase_ : Any): '''simple docstring''' cls._set_token_in_kwargs(lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = cls.get_config_dict(lowercase_ , **lowercase_) # get the text config dict if we are loading from BlipConfig if config_dict.get('''model_type''') == "blip": SCREAMING_SNAKE_CASE_ : str = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''') and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.') return cls.from_dict(lowercase_ , **lowercase_) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "blip_vision_model" def __init__( self : Optional[Any] , lowercase_ : Tuple=768 , lowercase_ : Tuple=3072 , lowercase_ : Tuple=512 , lowercase_ : int=12 , lowercase_ : Optional[int]=12 , lowercase_ : List[Any]=384 , lowercase_ : List[str]=16 , lowercase_ : Any="gelu" , lowercase_ : Optional[int]=1e-5 , lowercase_ : List[str]=0.0 , lowercase_ : List[str]=1e-10 , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE_ : List[str] = projection_dim SCREAMING_SNAKE_CASE_ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Dict = hidden_act @classmethod def _SCREAMING_SNAKE_CASE ( cls : str , lowercase_ : Union[str, os.PathLike] , **lowercase_ : int): '''simple docstring''' cls._set_token_in_kwargs(lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = cls.get_config_dict(lowercase_ , **lowercase_) # get the vision config dict if we are loading from BlipConfig if config_dict.get('''model_type''') == "blip": SCREAMING_SNAKE_CASE_ : int = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''') and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.') return cls.from_dict(lowercase_ , **lowercase_) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "blip" __UpperCamelCase = True def __init__( self : List[Any] , lowercase_ : str=None , lowercase_ : List[str]=None , lowercase_ : Tuple=512 , lowercase_ : Optional[Any]=2.65_92 , lowercase_ : Dict=256 , **lowercase_ : Tuple , ): '''simple docstring''' super().__init__(**lowercase_) if text_config is None: SCREAMING_SNAKE_CASE_ : Any = {} logger.info('''`text_config` is `None`. Initializing the `BlipTextConfig` with default values.''') if vision_config is None: SCREAMING_SNAKE_CASE_ : Dict = {} logger.info('''`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.''') SCREAMING_SNAKE_CASE_ : List[str] = BlipTextConfig(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = BlipVisionConfig(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.vision_config.hidden_size SCREAMING_SNAKE_CASE_ : List[str] = projection_dim SCREAMING_SNAKE_CASE_ : Union[str, Any] = logit_scale_init_value SCREAMING_SNAKE_CASE_ : List[Any] = 1.0 SCREAMING_SNAKE_CASE_ : Optional[int] = 0.02 SCREAMING_SNAKE_CASE_ : List[str] = image_text_hidden_size @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowercase_ : BlipTextConfig , lowercase_ : BlipVisionConfig , **lowercase_ : Any): '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.text_config.to_dict() SCREAMING_SNAKE_CASE_ : str = self.vision_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
91
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
1
"""simple docstring""" UpperCAmelCase_ : Dict = range(2, 20 + 1) UpperCAmelCase_ : Union[str, Any] = [10**k for k in range(ks[-1] + 1)] UpperCAmelCase_ : dict[int, dict[int, list[list[int]]]] = {} def _A (__a , __a , __a , __a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = sum(a_i[j] for j in range(__a , len(__a ) ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = sum(a_i[j] * base[j] for j in range(min(len(__a ) , __a ) ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0, 0 SCREAMING_SNAKE_CASE_ : str = n - i SCREAMING_SNAKE_CASE_ : Dict = memo.get(__a ) if sub_memo is not None: SCREAMING_SNAKE_CASE_ : str = sub_memo.get(__a ) if jumps is not None and len(__a ) > 0: # find and make the largest jump without going over SCREAMING_SNAKE_CASE_ : List[str] = -1 for _k in range(len(__a ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: SCREAMING_SNAKE_CASE_ : Optional[Any] = _k break if max_jump >= 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = jumps[max_jump] # since the difference between jumps is cached, add c SCREAMING_SNAKE_CASE_ : Optional[Any] = diff + c for j in range(min(__a , len(__a ) ) ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = divmod(__a , 10 ) if new_c > 0: add(__a , __a , __a ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = [] else: SCREAMING_SNAKE_CASE_ : List[Any] = {c: []} SCREAMING_SNAKE_CASE_ : Optional[int] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = next_term(__a , k - 1 , i + dn , __a ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = compute(__a , __a , i + dn , __a ) diff += _diff dn += terms_jumped SCREAMING_SNAKE_CASE_ : List[str] = sub_memo[c] # keep jumps sorted by # of terms skipped SCREAMING_SNAKE_CASE_ : List[Any] = 0 while j < len(__a ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(__a , (diff, dn, k) ) return (diff, dn) def _A (__a , __a , __a , __a ) -> Optional[int]: """simple docstring""" if i >= n: return 0, i if k > len(__a ): a_i.extend([0 for _ in range(k - len(__a ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) SCREAMING_SNAKE_CASE_ : Any = i SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = 0, 0, 0 for j in range(len(__a ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 SCREAMING_SNAKE_CASE_ : Dict = ds_c + ds_b diff += addend SCREAMING_SNAKE_CASE_ : Tuple = 0 for j in range(__a ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = a_i[j] + addend SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(__a , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(__a , __a , __a ) return diff, i - start_i def _A (__a , __a , __a ) -> Optional[Any]: """simple docstring""" for j in range(__a , len(__a ) ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = digits[j] + addend if s >= 10: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = divmod(__a , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = addend // 10 + quotient else: SCREAMING_SNAKE_CASE_ : Tuple = s SCREAMING_SNAKE_CASE_ : Tuple = addend // 10 if addend == 0: break while addend > 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = divmod(__a , 10 ) digits.append(__a ) def _A (__a = 10**15 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [1] SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : Dict = 0 while True: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = next_term(__a , 20 , i + dn , __a ) dn += terms_jumped if dn == n - i: break SCREAMING_SNAKE_CASE_ : List[str] = 0 for j in range(len(__a ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f'''{solution() = }''')
91
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
1
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
1
"""simple docstring""" import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : str , lowercase_ : Union[str, Any]=13 , lowercase_ : Dict=32 , lowercase_ : str=2 , lowercase_ : Union[str, Any]=3 , lowercase_ : List[str]=16 , lowercase_ : int=[32, 64, 128] , lowercase_ : List[Any]=[1, 2, 1] , lowercase_ : int=[2, 2, 4] , lowercase_ : str=2 , lowercase_ : Optional[Any]=2.0 , lowercase_ : List[str]=True , lowercase_ : List[str]=0.0 , lowercase_ : List[Any]=0.0 , lowercase_ : Tuple=0.1 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : int=False , lowercase_ : Dict=True , lowercase_ : int=0.02 , lowercase_ : Optional[Any]=1e-5 , lowercase_ : int=True , lowercase_ : Union[str, Any]=None , lowercase_ : List[str]=True , lowercase_ : Tuple=10 , lowercase_ : Any=8 , lowercase_ : Any=["stage1", "stage2"] , lowercase_ : str=[1, 2] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Optional[int] = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Optional[int] = embed_dim SCREAMING_SNAKE_CASE_ : Dict = hidden_sizes SCREAMING_SNAKE_CASE_ : str = depths SCREAMING_SNAKE_CASE_ : Any = num_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = window_size SCREAMING_SNAKE_CASE_ : List[str] = mlp_ratio SCREAMING_SNAKE_CASE_ : Any = qkv_bias SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = drop_path_rate SCREAMING_SNAKE_CASE_ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[Any] = use_absolute_embeddings SCREAMING_SNAKE_CASE_ : Optional[Any] = patch_norm SCREAMING_SNAKE_CASE_ : Any = layer_norm_eps SCREAMING_SNAKE_CASE_ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : Any = scope SCREAMING_SNAKE_CASE_ : str = use_labels SCREAMING_SNAKE_CASE_ : Tuple = type_sequence_label_size SCREAMING_SNAKE_CASE_ : str = encoder_stride SCREAMING_SNAKE_CASE_ : Any = out_features SCREAMING_SNAKE_CASE_ : List[str] = out_indices def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : str = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = FocalNetModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) SCREAMING_SNAKE_CASE_ : Any = int(config.embed_dim * 2 ** (len(config.depths) - 1)) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim)) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : List[Any] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = FocalNetBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : int = model(lowercase_) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.image_size, 8, 8]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1]) # verify backbone works with out_features=None SCREAMING_SNAKE_CASE_ : List[Any] = None SCREAMING_SNAKE_CASE_ : str = FocalNetBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : str = model(lowercase_) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.image_size * 2, 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = FocalNetForMaskedImageModeling(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase_) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : Any = FocalNetForMaskedImageModeling(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = model(lowercase_) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size)) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple , lowercase_ : str , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.type_sequence_label_size SCREAMING_SNAKE_CASE_ : Optional[int] = FocalNetForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images SCREAMING_SNAKE_CASE_ : Optional[int] = 1 SCREAMING_SNAKE_CASE_ : Optional[int] = FocalNetForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : str = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) __UpperCamelCase = ( {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification} if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = FocalNetModelTester(self) SCREAMING_SNAKE_CASE_ : List[str] = ConfigTester(self , config_class=lowercase_ , embed_dim=37 , has_text_modality=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' return def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) @unittest.skip(reason='''FocalNet does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' pass @unittest.skip(reason='''FocalNet does not use feedforward chunking''') def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) SCREAMING_SNAKE_CASE_ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_ , nn.Linear)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE_ : List[Any] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = outputs.hidden_states SCREAMING_SNAKE_CASE_ : List[Any] = getattr( self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths) + 1) self.assertEqual(len(lowercase_) , lowercase_) # FocalNet has a different seq_length SCREAMING_SNAKE_CASE_ : List[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE_ : List[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) SCREAMING_SNAKE_CASE_ : Optional[int] = outputs.reshaped_hidden_states self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = reshaped_hidden_states[0].shape SCREAMING_SNAKE_CASE_ : int = ( reshaped_hidden_states[0].view(lowercase_ , lowercase_ , height * width).permute(0 , 2 , 1) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Optional[int] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE_ : List[Any] = True self.check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : List[str] = True self.check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[str] = 3 SCREAMING_SNAKE_CASE_ : Any = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE_ : Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE_ : Any = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE_ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: SCREAMING_SNAKE_CASE_ : Any = True self.check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ , (padded_height, padded_width)) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Dict = True self.check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ , (padded_height, padded_width)) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = FocalNetModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Dict = _config_zero_init(lowercase_) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : List[str] = model_class(config=lowercase_) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return AutoImageProcessor.from_pretrained('''microsoft/focalnet-tiny''') if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny''').to(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.default_image_processor SCREAMING_SNAKE_CASE_ : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''') SCREAMING_SNAKE_CASE_ : str = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor([0.21_66, -0.43_68, 0.21_91]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4)) self.assertTrue(outputs.logits.argmax(dim=-1).item() , 281) @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (FocalNetBackbone,) if is_torch_available() else () __UpperCamelCase = FocalNetConfig __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = FocalNetModelTester(self)
91
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
91
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
1
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
91
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is None: return [1] + ([0] * len(lowercase_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "CLIPImageProcessor" __UpperCamelCase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : List[Any] , lowercase_ : Dict=None , lowercase_ : List[str]=None , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , lowercase_ , ) SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''feature_extractor''') SCREAMING_SNAKE_CASE_ : Union[str, 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__(lowercase_ , lowercase_) def __call__( self : str , lowercase_ : int=None , lowercase_ : int=None , lowercase_ : Dict=None , **lowercase_ : Any): '''simple docstring''' if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''') if text is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer(lowercase_ , return_tensors=lowercase_ , **lowercase_) if images is not None: SCREAMING_SNAKE_CASE_ : Dict = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_) if text is not None and images is not None: SCREAMING_SNAKE_CASE_ : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowercase_) , tensor_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : int , **lowercase_ : Any): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , *lowercase_ : Union[str, Any] , **lowercase_ : Optional[int]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_) @property def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE_ : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowercase_ , ) return self.image_processor_class @property def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowercase_ , ) return self.image_processor
91
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : str = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_))
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ : Optional[Any] = { """configuration_timesformer""": ["""TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimesformerConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ """TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TimesformerModel""", """TimesformerForVideoClassification""", """TimesformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys UpperCAmelCase_ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
1
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar UpperCAmelCase_ : int = TypeVar("""T""") class lowerCAmelCase__ ( Generic[T] ): '''simple docstring''' def __init__( self : Optional[int] , lowercase_ : T): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = data SCREAMING_SNAKE_CASE_ : Node[T] | None = None def __str__( self : Union[str, Any]): '''simple docstring''' return F'{self.data}' class lowerCAmelCase__ ( Generic[T] ): '''simple docstring''' def __init__( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Node[T] | None = None def __iter__( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.top while node: yield node.data SCREAMING_SNAKE_CASE_ : Union[str, Any] = node.next def __str__( self : Union[str, Any]): '''simple docstring''' return "->".join([str(lowercase_) for item in self]) def __len__( self : Union[str, Any]): '''simple docstring''' return len(tuple(iter(self))) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return self.top is None def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : T): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = Node(lowercase_) if not self.is_empty(): SCREAMING_SNAKE_CASE_ : Optional[int] = self.top SCREAMING_SNAKE_CASE_ : Optional[Any] = node def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' if self.is_empty(): raise IndexError('''pop from empty stack''') assert isinstance(self.top , lowercase_) SCREAMING_SNAKE_CASE_ : int = self.top SCREAMING_SNAKE_CASE_ : int = self.top.next return pop_node.data def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' if self.is_empty(): raise IndexError('''peek from empty stack''') assert self.top is not None return self.top.data def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = None if __name__ == "__main__": from doctest import testmod testmod()
91
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
1
"""simple docstring""" 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 lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "Pix2StructImageProcessor" __UpperCamelCase = ("T5Tokenizer", "T5TokenizerFast") def __init__( self : Any , lowercase_ : Dict , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = False super().__init__(lowercase_ , lowercase_) def __call__( self : Dict , lowercase_ : Optional[int]=None , lowercase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowercase_ : bool = True , lowercase_ : Union[bool, str, PaddingStrategy] = False , lowercase_ : Union[bool, str, TruncationStrategy] = None , lowercase_ : Optional[int] = None , lowercase_ : Optional[int] = 2048 , lowercase_ : int = 0 , lowercase_ : Optional[int] = None , lowercase_ : Optional[bool] = None , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = True , lowercase_ : Optional[Union[str, TensorType]] = None , **lowercase_ : List[str] , ): '''simple docstring''' if images is None and text is None: raise ValueError('''You have to specify either images or text.''') # Get only text if images is None and not self.image_processor.is_vqa: SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer( text=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_token_type_ids=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values SCREAMING_SNAKE_CASE_ : Any = self.image_processor( lowercase_ , return_tensors=lowercase_ , max_patches=lowercase_ , **lowercase_) else: # add pixel_values and bbox SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processor( lowercase_ , return_tensors=lowercase_ , max_patches=lowercase_ , header_text=lowercase_ , **lowercase_) if text is not None and not self.image_processor.is_vqa: SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer( text=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_token_type_ids=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) if "attention_mask" in text_encoding: SCREAMING_SNAKE_CASE_ : List[Any] = text_encoding.pop('''attention_mask''') if "input_ids" in text_encoding: SCREAMING_SNAKE_CASE_ : Dict = text_encoding.pop('''input_ids''') else: SCREAMING_SNAKE_CASE_ : str = None if text_encoding is not None: encoding_image_processor.update(lowercase_) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowercase_ : str , **lowercase_ : List[str]): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , *lowercase_ : List[Any] , **lowercase_ : Any): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_) @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
91
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
1
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Optional[Any] = { """configuration_funnel""": ["""FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FunnelConfig"""], """convert_funnel_original_tf_checkpoint_to_pytorch""": [], """tokenization_funnel""": ["""FunnelTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = ["""FunnelTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = [ """FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """FunnelBaseModel""", """FunnelForMaskedLM""", """FunnelForMultipleChoice""", """FunnelForPreTraining""", """FunnelForQuestionAnswering""", """FunnelForSequenceClassification""", """FunnelForTokenClassification""", """FunnelModel""", """FunnelPreTrainedModel""", """load_tf_weights_in_funnel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : str = [ """TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFFunnelBaseModel""", """TFFunnelForMaskedLM""", """TFFunnelForMultipleChoice""", """TFFunnelForPreTraining""", """TFFunnelForQuestionAnswering""", """TFFunnelForSequenceClassification""", """TFFunnelForTokenClassification""", """TFFunnelModel""", """TFFunnelPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys UpperCAmelCase_ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
1
"""simple docstring""" import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any]=7 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=18 , lowercase_ : str=30 , lowercase_ : int=400 , lowercase_ : Optional[int]=True , lowercase_ : Optional[Any]=None , lowercase_ : Union[str, Any]=True , lowercase_ : List[str]=None , lowercase_ : List[Any]=True , lowercase_ : Optional[int]=[0.5, 0.5, 0.5] , lowercase_ : List[Any]=[0.5, 0.5, 0.5] , lowercase_ : List[Any]=False , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = size if size is not None else {'''height''': 20, '''width''': 20} SCREAMING_SNAKE_CASE_ : Dict = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} SCREAMING_SNAKE_CASE_ : List[Any] = parent SCREAMING_SNAKE_CASE_ : Dict = batch_size SCREAMING_SNAKE_CASE_ : Any = num_channels SCREAMING_SNAKE_CASE_ : List[str] = image_size SCREAMING_SNAKE_CASE_ : Any = min_resolution SCREAMING_SNAKE_CASE_ : Dict = max_resolution SCREAMING_SNAKE_CASE_ : List[str] = do_resize SCREAMING_SNAKE_CASE_ : Any = size SCREAMING_SNAKE_CASE_ : Any = do_center_crop SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[Any] = image_mean SCREAMING_SNAKE_CASE_ : Optional[int] = image_std SCREAMING_SNAKE_CASE_ : int = do_reduce_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def _A () -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) SCREAMING_SNAKE_CASE_ : Tuple = Image.open(dataset[0]['''file'''] ) SCREAMING_SNAKE_CASE_ : str = Image.open(dataset[1]['''file'''] ) return image, map def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = Image.open(ds[0]['''file'''] ) SCREAMING_SNAKE_CASE_ : List[Any] = Image.open(ds[1]['''file'''] ) SCREAMING_SNAKE_CASE_ : Any = Image.open(ds[2]['''file'''] ) SCREAMING_SNAKE_CASE_ : Optional[int] = Image.open(ds[3]['''file'''] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = BeitImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = BeitImageProcessingTester(self) @property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(lowercase_ , '''do_resize''')) self.assertTrue(hasattr(lowercase_ , '''size''')) self.assertTrue(hasattr(lowercase_ , '''do_center_crop''')) self.assertTrue(hasattr(lowercase_ , '''center_crop''')) self.assertTrue(hasattr(lowercase_ , '''do_normalize''')) self.assertTrue(hasattr(lowercase_ , '''image_mean''')) self.assertTrue(hasattr(lowercase_ , '''image_std''')) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'''height''': 20, '''width''': 20}) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18}) self.assertEqual(image_processor.do_reduce_labels , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=lowercase_) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42}) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84}) self.assertEqual(image_processor.do_reduce_labels , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE_ : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(lowercase_ , 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , numpify=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , np.ndarray) # Test not batched input SCREAMING_SNAKE_CASE_ : int = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase_ , 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , torchify=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , torch.Tensor) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[Any] = image_processing(lowercase_ , 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , torchify=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for image in image_inputs: self.assertIsInstance(lowercase_ , torch.Tensor) maps.append(torch.zeros(image.shape[-2:]).long()) # Test not batched input SCREAMING_SNAKE_CASE_ : List[str] = image_processing(image_inputs[0] , maps[0] , return_tensors='''pt''') self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long) self.assertTrue(encoding['''labels'''].min().item() >= 0) self.assertTrue(encoding['''labels'''].max().item() <= 255) # Test batched SCREAMING_SNAKE_CASE_ : List[Any] = image_processing(lowercase_ , lowercase_ , return_tensors='''pt''') self.assertEqual( encoding['''pixel_values'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long) self.assertTrue(encoding['''labels'''].min().item() >= 0) self.assertTrue(encoding['''labels'''].max().item() <= 255) # Test not batched input (PIL images) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = prepare_semantic_single_inputs() SCREAMING_SNAKE_CASE_ : List[Any] = image_processing(lowercase_ , lowercase_ , return_tensors='''pt''') self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long) self.assertTrue(encoding['''labels'''].min().item() >= 0) self.assertTrue(encoding['''labels'''].max().item() <= 255) # Test batched input (PIL images) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = prepare_semantic_batch_inputs() SCREAMING_SNAKE_CASE_ : Tuple = image_processing(lowercase_ , lowercase_ , return_tensors='''pt''') self.assertEqual( encoding['''pixel_values'''].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 2, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long) self.assertTrue(encoding['''labels'''].min().item() >= 0) self.assertTrue(encoding['''labels'''].max().item() <= 255) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.image_processing_class(**self.image_processor_dict) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_semantic_single_inputs() SCREAMING_SNAKE_CASE_ : Any = image_processing(lowercase_ , lowercase_ , return_tensors='''pt''') self.assertTrue(encoding['''labels'''].min().item() >= 0) self.assertTrue(encoding['''labels'''].max().item() <= 150) SCREAMING_SNAKE_CASE_ : Tuple = True SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(lowercase_ , lowercase_ , return_tensors='''pt''') self.assertTrue(encoding['''labels'''].min().item() >= 0) self.assertTrue(encoding['''labels'''].max().item() <= 255)
91
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
1
"""simple docstring""" from __future__ import annotations import math def _A (__a , __a , __a , __a , __a ) -> int: """simple docstring""" if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if not scores: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __a , __a , __a ) , minimax(depth + 1 , node_index * 2 + 1 , __a , __a , __a ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __a , __a , __a ) , minimax(depth + 1 , node_index * 2 + 1 , __a , __a , __a ) , ) ) def _A () -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [90, 23, 6, 33, 21, 65, 1_23, 3_44_23] SCREAMING_SNAKE_CASE_ : Any = math.log(len(__a ) , 2 ) print(f'Optimal value : {minimax(0 , 0 , __a , __a , __a )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' debug_launcher(test_script.main) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' debug_launcher(test_ops.main)
91
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : int = logging.get_logger(__name__) UpperCAmelCase_ : Union[str, Any] = { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""", """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""", } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "roberta" def __init__( self : List[Any] , lowercase_ : Optional[Any]=50265 , lowercase_ : List[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Optional[Any]=12 , lowercase_ : Any=3072 , lowercase_ : Tuple="gelu" , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=512 , lowercase_ : Optional[int]=2 , lowercase_ : List[str]=0.02 , lowercase_ : Tuple=1e-12 , lowercase_ : Any=1 , lowercase_ : Any=0 , lowercase_ : Optional[int]=2 , lowercase_ : Optional[int]="absolute" , lowercase_ : str=True , lowercase_ : str=None , **lowercase_ : int , ): '''simple docstring''' super().__init__(pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : Any = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : str = position_embedding_type SCREAMING_SNAKE_CASE_ : Union[str, Any] = use_cache SCREAMING_SNAKE_CASE_ : Tuple = classifier_dropout class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Union[str, Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE_ : Optional[Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ])
91
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
1
"""simple docstring""" import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset UpperCAmelCase_ : Union[str, Any] = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : str , lowercase_ : Optional[int]): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : List[str] = torchvision.models.resnetaaa(pretrained=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = list(model.children())[:-2] SCREAMING_SNAKE_CASE_ : List[Any] = nn.Sequential(*lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds]) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.pool(self.model(lowercase_)) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.flatten(lowercase_ , start_dim=2) SCREAMING_SNAKE_CASE_ : Dict = out.transpose(1 , 2).contiguous() return out # BxNx2048 class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : str , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [json.loads(lowercase_) for l in open(lowercase_)] SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.dirname(lowercase_) SCREAMING_SNAKE_CASE_ : int = tokenizer SCREAMING_SNAKE_CASE_ : Union[str, Any] = labels SCREAMING_SNAKE_CASE_ : List[str] = len(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE_ : Optional[Any] = transforms def __len__( self : List[Any]): '''simple docstring''' return len(self.data) def __getitem__( self : Optional[Any] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.LongTensor(self.tokenizer.encode(self.data[index]['''text'''] , add_special_tokens=lowercase_)) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = sentence[0], sentence[1:-1], sentence[-1] SCREAMING_SNAKE_CASE_ : Any = sentence[: self.max_seq_length] SCREAMING_SNAKE_CASE_ : Tuple = torch.zeros(self.n_classes) SCREAMING_SNAKE_CASE_ : List[Any] = 1 SCREAMING_SNAKE_CASE_ : List[Any] = Image.open(os.path.join(self.data_dir , self.data[index]['''img'''])).convert('''RGB''') SCREAMING_SNAKE_CASE_ : Tuple = self.transforms(lowercase_) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = Counter() for row in self.data: label_freqs.update(row['''label''']) return label_freqs def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [len(row['''sentence'''] ) for row in batch] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = len(__a ), max(__a ) SCREAMING_SNAKE_CASE_ : Tuple = torch.zeros(__a , __a , dtype=torch.long ) SCREAMING_SNAKE_CASE_ : Dict = torch.zeros(__a , __a , dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(__a , __a ) ): SCREAMING_SNAKE_CASE_ : Any = input_row['''sentence'''] SCREAMING_SNAKE_CASE_ : Tuple = 1 SCREAMING_SNAKE_CASE_ : Dict = torch.stack([row['''image'''] for row in batch] ) SCREAMING_SNAKE_CASE_ : Dict = torch.stack([row['''label'''] for row in batch] ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.stack([row['''image_start_token'''] for row in batch] ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.stack([row['''image_end_token'''] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def _A () -> Tuple: """simple docstring""" return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def _A () -> List[str]: """simple docstring""" return transforms.Compose( [ transforms.Resize(2_56 ), transforms.CenterCrop(2_24 ), transforms.ToTensor(), transforms.Normalize( mean=[0.46_77_70_44, 0.44_53_14_29, 0.40_66_10_17] , std=[0.12_22_19_94, 0.12_14_58_35, 0.14_38_04_69] , ), ] )
91
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase_ : int = { """configuration_poolformer""": [ """POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PoolFormerConfig""", """PoolFormerOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = ["""PoolFormerFeatureExtractor"""] UpperCAmelCase_ : int = ["""PoolFormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = [ """POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PoolFormerForImageClassification""", """PoolFormerModel""", """PoolFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys UpperCAmelCase_ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
91
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''') if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''') if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
1
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger UpperCAmelCase_ : Union[str, Any] = """<<<<<<< This should probably be modified because it mentions: """ UpperCAmelCase_ : Optional[Any] = """======= >>>>>>> """ UpperCAmelCase_ : Union[str, Any] = [ """TextEncoderConfig""", """ByteTextEncoder""", """SubwordTextEncoder""", """encoder_config""", """maybe_build_from_corpus""", """manual_dir""", ] UpperCAmelCase_ : List[str] = [ # (pattern, replacement) # Order is important here for some replacements (r"""tfds\.core""", r"""datasets"""), (r"""tf\.io\.gfile\.GFile""", r"""open"""), (r"""tf\.([\w\d]+)""", r"""datasets.Value('\1')"""), (r"""tfds\.features\.Text\(\)""", r"""datasets.Value('string')"""), (r"""tfds\.features\.Text\(""", r"""datasets.Value('string'),"""), (r"""features\s*=\s*tfds.features.FeaturesDict\(""", r"""features=datasets.Features("""), (r"""tfds\.features\.FeaturesDict\(""", r"""dict("""), (r"""The TensorFlow Datasets Authors""", r"""The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"""), (r"""tfds\.""", r"""datasets."""), (r"""dl_manager\.manual_dir""", r"""self.config.data_dir"""), (r"""self\.builder_config""", r"""self.config"""), ] def _A (__a ) -> Optional[int]: """simple docstring""" return ConvertCommand(args.tfds_path , args.datasets_directory ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( lowercase_ : ArgumentParser): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = parser.add_parser( '''convert''' , help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.''' , ) train_parser.add_argument( '''--tfds_path''' , type=lowercase_ , required=lowercase_ , help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.''' , ) train_parser.add_argument( '''--datasets_directory''' , type=lowercase_ , required=lowercase_ , help='''Path to the HuggingFace Datasets folder.''') train_parser.set_defaults(func=lowercase_) def __init__( self : Union[str, Any] , lowercase_ : str , lowercase_ : str , *lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = get_logger('''datasets-cli/converting''') SCREAMING_SNAKE_CASE_ : Optional[Any] = tfds_path SCREAMING_SNAKE_CASE_ : Tuple = datasets_directory def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' if os.path.isdir(self._tfds_path): SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.abspath(self._tfds_path) elif os.path.isfile(self._tfds_path): SCREAMING_SNAKE_CASE_ : List[str] = os.path.dirname(self._tfds_path) else: raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.''') SCREAMING_SNAKE_CASE_ : Any = os.path.abspath(self._datasets_directory) self._logger.info(F'Converting datasets from {abs_tfds_path} to {abs_datasets_path}') SCREAMING_SNAKE_CASE_ : Optional[int] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} if os.path.isdir(self._tfds_path): SCREAMING_SNAKE_CASE_ : List[str] = os.listdir(lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = [os.path.basename(self._tfds_path)] for f_name in file_names: self._logger.info(F'Looking at file {f_name}') SCREAMING_SNAKE_CASE_ : Tuple = os.path.join(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Any = os.path.join(lowercase_ , lowercase_) if not os.path.isfile(lowercase_) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('''Skipping file''') continue with open(lowercase_ , encoding='''utf-8''') as f: SCREAMING_SNAKE_CASE_ : Any = f.readlines() SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : Dict = False SCREAMING_SNAKE_CASE_ : Any = False SCREAMING_SNAKE_CASE_ : List[str] = [] for line in lines: SCREAMING_SNAKE_CASE_ : List[Any] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE_ : List[str] = '''import datasets\n''' elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''''' continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE_ : str = '''from datasets import logging\n''' elif "getLogger" in out_line: SCREAMING_SNAKE_CASE_ : List[str] = out_line.replace('''getLogger''' , '''get_logger''') elif any(expression in out_line for expression in TO_HIGHLIGHT): SCREAMING_SNAKE_CASE_ : Optional[Any] = True SCREAMING_SNAKE_CASE_ : Dict = list(filter(lambda lowercase_: e in out_line , lowercase_)) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowercase_) + '''\n''') out_lines.append(lowercase_) out_lines.append(lowercase_) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE_ : List[Any] = re.sub(lowercase_ , lowercase_ , lowercase_) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE_ : Any = re.match(r'''from\stensorflow_datasets.*import\s([^\.\r\n]+)''' , lowercase_) tfds_imports.extend(imp.strip() for imp in match.group(1).split(''',''')) SCREAMING_SNAKE_CASE_ : str = '''from . import ''' + match.group(1) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(F'Error converting {out_line.strip()}') if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE_ : List[str] = True out_lines.append(lowercase_) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE_ : List[Any] = f_name.replace('''.py''' , '''''') SCREAMING_SNAKE_CASE_ : Any = os.path.join(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = os.path.join(lowercase_ , lowercase_) os.makedirs(lowercase_ , exist_ok=lowercase_) self._logger.info(F'Adding directory {output_dir}') imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}) else: # Utilities will be moved at the end utils_files.append(lowercase_) if needs_manual_update: with_manual_update.append(lowercase_) with open(lowercase_ , '''w''' , encoding='''utf-8''') as f: f.writelines(lowercase_) self._logger.info(F'Converted in {output_file}') for utils_file in utils_files: try: SCREAMING_SNAKE_CASE_ : Tuple = os.path.basename(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = imports_to_builder_map[f_name.replace('''.py''' , '''''')] self._logger.info(F'Moving {dest_folder} to {utils_file}') shutil.copy(lowercase_ , lowercase_) except KeyError: self._logger.error(F'Cannot find destination folder for {utils_file}. Please copy manually.') if with_manual_update: for file_path in with_manual_update: self._logger.warning( F'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.')
91
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
1
"""simple docstring""" from __future__ import annotations def _A (__a , __a , __a ) -> int | float: """simple docstring""" if len(__a ) == 0: raise ValueError('''find_max() arg is an empty sequence''' ) if ( left >= len(__a ) or left < -len(__a ) or right >= len(__a ) or right < -len(__a ) ): raise IndexError('''list index out of range''' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE_ : str = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE_ : int = find_max(__a , __a , __a ) # find max in range[left, mid] SCREAMING_SNAKE_CASE_ : List[str] = find_max(__a , mid + 1 , __a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
91
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
1
"""simple docstring""" def _A (__a ) -> list: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = len(__a ) for i in range(1 , __a ): SCREAMING_SNAKE_CASE_ : int = collection[i] SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = i - 1 while low <= high: SCREAMING_SNAKE_CASE_ : Any = (low + high) // 2 if val < collection[mid]: SCREAMING_SNAKE_CASE_ : str = mid - 1 else: SCREAMING_SNAKE_CASE_ : Dict = mid + 1 for j in range(__a , __a , -1 ): SCREAMING_SNAKE_CASE_ : Optional[int] = collection[j - 1] SCREAMING_SNAKE_CASE_ : Optional[Any] = val return collection if __name__ == "__main__": UpperCAmelCase_ : List[str] = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase_ : Union[str, Any] = [int(item) for item in user_input.split(""",""")] print(binary_insertion_sort(unsorted))
91
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase_ : Any = { """configuration_cpmant""": ["""CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CpmAntConfig"""], """tokenization_cpmant""": ["""CpmAntTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = [ """CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST""", """CpmAntForCausalLM""", """CpmAntModel""", """CpmAntPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''') if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''') if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
1
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy UpperCAmelCase_ : Tuple = logging.getLogger(__name__) def _A (__a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = bnb_quantization_config.load_in_abit SCREAMING_SNAKE_CASE_ : List[Any] = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( '''You have a version of `bitsandbytes` that is not compatible with 8bit quantization,''' ''' make sure you have the latest version of `bitsandbytes` installed.''' ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( '''You have a version of `bitsandbytes` that is not compatible with 4bit quantization,''' '''make sure you have the latest version of `bitsandbytes` installed.''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: SCREAMING_SNAKE_CASE_ : int = [key for key, value in device_map.items() if value in ['''disk''', '''cpu''']] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: SCREAMING_SNAKE_CASE_ : Optional[int] = get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) SCREAMING_SNAKE_CASE_ : int = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : Tuple = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft SCREAMING_SNAKE_CASE_ : int = load_in_abit SCREAMING_SNAKE_CASE_ : Any = load_in_abit SCREAMING_SNAKE_CASE_ : Any = get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( '''It is not recommended to quantize a loaded model. ''' '''The model should be instantiated under the `init_empty_weights` context manager.''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype SCREAMING_SNAKE_CASE_ : int = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: SCREAMING_SNAKE_CASE_ : List[Any] = name.replace('''.weight''' , '''''' ).replace('''.bias''' , '''''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info( f'The model device type is {model_device.type}. However, cuda is needed for quantization.' '''We move the model to cuda.''' ) return model elif weights_location is None: raise RuntimeError( f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' ) else: with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): SCREAMING_SNAKE_CASE_ : Dict = True SCREAMING_SNAKE_CASE_ : List[str] = any(x in list(device_map.values() ) for x in ['''cpu''', '''disk'''] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def _A (__a , __a , __a=None , __a=None , __a=None ) -> Union[str, Any]: """simple docstring""" if device_map is None: if torch.cuda.is_available(): SCREAMING_SNAKE_CASE_ : List[Any] = {'''''': torch.cuda.current_device()} else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info('''The device_map was not initialized.''' '''Setting device_map to `{\'\':torch.cuda.current_device()}`.''' ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( '''If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or ''' '''\'sequential\'.''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) SCREAMING_SNAKE_CASE_ : int = {} SCREAMING_SNAKE_CASE_ : List[Any] = special_dtypes SCREAMING_SNAKE_CASE_ : Union[str, Any] = no_split_module_classes SCREAMING_SNAKE_CASE_ : List[Any] = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_balanced_memory( __a , low_zero=(device_map == '''balanced_low_0''') , max_memory=__a , **__a , ) SCREAMING_SNAKE_CASE_ : List[str] = max_memory SCREAMING_SNAKE_CASE_ : List[Any] = infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu SCREAMING_SNAKE_CASE_ : int = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules SCREAMING_SNAKE_CASE_ : Dict = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( ''' Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. ''' ) else: logger.info( '''Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit''' ) del device_map_without_some_modules return device_map def _A (__a , __a , __a=None , __a=None ) -> str: """simple docstring""" if modules_to_not_convert is None: SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = _replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def _A (__a , __a , __a=None , __a=None , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = False for name, module in model.named_children(): if current_key_name is None: SCREAMING_SNAKE_CASE_ : Dict = [] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` SCREAMING_SNAKE_CASE_ : int = '''.'''.join(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: SCREAMING_SNAKE_CASE_ : int = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE_ : Dict = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE_ : int = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError('''load_in_8bit and load_in_4bit can\'t be both False''' ) SCREAMING_SNAKE_CASE_ : int = module.weight.data if module.bias is not None: SCREAMING_SNAKE_CASE_ : List[Any] = module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) SCREAMING_SNAKE_CASE_ : Optional[int] = True if len(list(module.children() ) ) > 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = _replace_with_bnb_layers( __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _A (__a ) -> Any: """simple docstring""" with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` SCREAMING_SNAKE_CASE_ : Any = find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : int = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: SCREAMING_SNAKE_CASE_ : List[str] = sum(__a , [] ) SCREAMING_SNAKE_CASE_ : Dict = len(__a ) > 0 # Check if it is a base model SCREAMING_SNAKE_CASE_ : Tuple = False if hasattr(__a , '''base_model_prefix''' ): SCREAMING_SNAKE_CASE_ : int = not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head SCREAMING_SNAKE_CASE_ : str = list(model.named_children() ) SCREAMING_SNAKE_CASE_ : List[str] = [list_modules[-1][0]] # add last module together with tied weights SCREAMING_SNAKE_CASE_ : Any = set(__a ) - set(__a ) SCREAMING_SNAKE_CASE_ : Tuple = list(set(__a ) ) + list(__a ) # remove ".weight" from the keys SCREAMING_SNAKE_CASE_ : int = ['''.weight''', '''.bias'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = name.replace(__a , '''''' ) filtered_module_names.append(__a ) return filtered_module_names def _A (__a ) -> Any: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def _A (__a ) -> Union[str, Any]: """simple docstring""" return next(parameter.parameters() ).device def _A (__a , __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) SCREAMING_SNAKE_CASE_ : List[Any] = param_name SCREAMING_SNAKE_CASE_ : List[str] = model if "." in tensor_name: SCREAMING_SNAKE_CASE_ : List[str] = tensor_name.split('''.''' ) for split in splits[:-1]: SCREAMING_SNAKE_CASE_ : str = getattr(__a , __a ) if new_module is None: raise ValueError(f'{module} has no attribute {split}.' ) SCREAMING_SNAKE_CASE_ : List[Any] = new_module SCREAMING_SNAKE_CASE_ : Optional[Any] = splits[-1] # offload weights SCREAMING_SNAKE_CASE_ : Optional[Any] = False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , '''SCB''' ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace('''weight''' , '''SCB''' ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace('''weight''' , '''SCB''' ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , '''meta''' , dtype=__a , value=torch.empty(*param.size() ) )
91
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
1
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase_ : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Tuple , lowercase_ : bool = True , lowercase_ : Optional[Dict[str, int]] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : str , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : str = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : int = get_size_dict(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = do_resize SCREAMING_SNAKE_CASE_ : int = size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : int = do_center_crop SCREAMING_SNAKE_CASE_ : List[Any] = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = do_rescale SCREAMING_SNAKE_CASE_ : Optional[int] = rescale_factor SCREAMING_SNAKE_CASE_ : str = do_normalize SCREAMING_SNAKE_CASE_ : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : List[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BICUBIC , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}') SCREAMING_SNAKE_CASE_ : int = get_resize_output_image_size(lowercase_ , size=size['''shortest_edge'''] , default_to_square=lowercase_) return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : np.ndarray , lowercase_ : float , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str]): '''simple docstring''' return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : str , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : ImageInput , lowercase_ : Optional[bool] = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : Optional[bool] = None , lowercase_ : Optional[float] = None , lowercase_ : Optional[bool] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowercase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : int = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Dict = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Any = get_size_dict(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : List[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : List[Any] = make_list_of_images(lowercase_) if not valid_images(lowercase_): 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: raise ValueError('''Size 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. SCREAMING_SNAKE_CASE_ : Union[str, Any] = [to_numpy_array(lowercase_) for image in images] if do_resize: SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE_ : Tuple = [self.center_crop(image=lowercase_ , size=lowercase_) for image in images] if do_rescale: SCREAMING_SNAKE_CASE_ : int = [self.rescale(image=lowercase_ , scale=lowercase_) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_ : Optional[int] = [self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) for image in images] SCREAMING_SNAKE_CASE_ : Any = [to_channel_dimension_format(lowercase_ , lowercase_) for image in images] SCREAMING_SNAKE_CASE_ : Dict = {'''pixel_values''': images} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''') SCREAMING_SNAKE_CASE_ : Dict = { '''input_ids''': tf.convert_to_tensor([[0, 2646, 10269, 83, 99942, 2]] , dtype=tf.intaa), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa), } SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase_)['''last_hidden_state'''] SCREAMING_SNAKE_CASE_ : List[Any] = tf.TensorShape((1, 6, 768)) self.assertEqual(output.shape , lowercase_) # compare the actual values for a slice. SCREAMING_SNAKE_CASE_ : int = tf.convert_to_tensor( [ [ [0.0_68_17_62, 0.10_89_44_51, 0.06_77_25_04], [-0.06_42_36_68, 0.02_36_66_15, 0.04_32_93_44], [-0.06_05_72_95, 0.09_97_41_35, -0.00_07_05_84], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4))
91
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
1
"""simple docstring""" from functools import reduce UpperCAmelCase_ : Tuple = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def _A (__a = N ) -> int: """simple docstring""" return max( # mypy cannot properly interpret reduce int(reduce(lambda __a , __a : str(int(__a ) * int(__a ) ) , n[i : i + 13] ) ) for i in range(len(__a ) - 12 ) ) if __name__ == "__main__": print(f'''{solution() = }''')
91
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is None: return [1] + ([0] * len(lowercase_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
1
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = checkpoints.load_tax_checkpoint(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = flatten_dict(__a ) return flax_params def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''token_embedder''': '''embeddings''', '''encoder_norm''': '''layernorm''', '''kernel''': '''weight''', '''.out''': '''.output''', '''scale''': '''weight''', '''embedders_0.pos_embedding''': '''row_embedder.weight''', '''embedders_1.pos_embedding''': '''column_embedder.weight''', } SCREAMING_SNAKE_CASE_ : Any = { '''query''': '''attention.query''', '''key''': '''attention.key''', '''value''': '''attention.value''', '''output.dense''': '''output''', '''encoder_decoder_attention.o''': '''encoder_decoder_attention.attention.o''', '''pre_self_attention_layer_norm''': '''self_attention.layer_norm''', '''pre_cross_attention_layer_norm''': '''encoder_decoder_attention.layer_norm''', '''mlp.''': '''mlp.DenseReluDense.''', '''pre_mlp_layer_norm''': '''mlp.layer_norm''', '''self_attention.o''': '''self_attention.attention.o''', '''decoder.embeddings.embedding''': '''decoder.embed_tokens.weight''', '''decoder.relpos_bias.rel_embedding''': '''decoder.layer.0.self_attention.attention.relative_attention_bias.weight''', '''decoder.decoder_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.logits_dense.weight''': '''decoder.lm_head.weight''', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key SCREAMING_SNAKE_CASE_ : str = '''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): SCREAMING_SNAKE_CASE_ : str = new_key.replace(__a , __a ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): SCREAMING_SNAKE_CASE_ : Any = new_key.replace(__a , __a ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number SCREAMING_SNAKE_CASE_ : int = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __a ) SCREAMING_SNAKE_CASE_ : Tuple = new_key.replace('''encoder''' , '''encoder.encoder''' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number SCREAMING_SNAKE_CASE_ : Any = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __a ) SCREAMING_SNAKE_CASE_ : str = flax_dict[key] SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): SCREAMING_SNAKE_CASE_ : List[Any] = torch.from_numpy(converted_dict[key].T ) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def _A (__a , __a , __a=False , __a=False ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_flax_param(__a ) if not use_large: SCREAMING_SNAKE_CASE_ : Optional[int] = PixaStructVisionConfig() SCREAMING_SNAKE_CASE_ : int = PixaStructTextConfig() else: SCREAMING_SNAKE_CASE_ : Dict = PixaStructVisionConfig( hidden_size=15_36 , d_ff=39_68 , num_attention_heads=24 , num_hidden_layers=18 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = PixaStructTextConfig(hidden_size=15_36 , d_ff=39_68 , num_heads=24 , num_layers=18 ) SCREAMING_SNAKE_CASE_ : Tuple = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__a ) SCREAMING_SNAKE_CASE_ : Dict = PixaStructForConditionalGeneration(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = rename_and_convert_flax_params(__a ) model.load_state_dict(__a ) SCREAMING_SNAKE_CASE_ : Tuple = AutoTokenizer.from_pretrained('''ybelkada/test-pix2struct-tokenizer''' ) SCREAMING_SNAKE_CASE_ : List[str] = PixaStructImageProcessor() SCREAMING_SNAKE_CASE_ : str = PixaStructProcessor(image_processor=__a , tokenizer=__a ) if use_large: SCREAMING_SNAKE_CASE_ : int = 40_96 SCREAMING_SNAKE_CASE_ : int = True # mkdir if needed os.makedirs(__a , exist_ok=__a ) model.save_pretrained(__a ) processor.save_pretrained(__a ) print('''Model saved in {}'''.format(__a ) ) if __name__ == "__main__": UpperCAmelCase_ : Any = argparse.ArgumentParser() parser.add_argument("""--t5x_checkpoint_path""", default=None, type=str, help="""Path to the original T5x checkpoint.""") parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--use_large""", action="""store_true""", help="""Use large model.""") parser.add_argument("""--is_vqa""", action="""store_true""", help="""Use large model.""") UpperCAmelCase_ : str = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
91
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : str = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_))
91
1
"""simple docstring""" from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor"] __UpperCamelCase = "SamImageProcessor" def __init__( self : List[str] , lowercase_ : Tuple): '''simple docstring''' super().__init__(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = -10 SCREAMING_SNAKE_CASE_ : int = self.image_processor.size['''longest_edge'''] def __call__( self : Tuple , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=None , lowercase_ : Any=None , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Union[str, TensorType]] = None , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor( lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) # pop arguments that are not used in the foward but used nevertheless SCREAMING_SNAKE_CASE_ : Optional[Any] = encoding_image_processor['''original_sizes'''] if hasattr(lowercase_ , '''numpy'''): # Checks if Torch or TF tensor SCREAMING_SNAKE_CASE_ : List[Any] = original_sizes.numpy() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = self._check_and_preprocess_points( input_points=lowercase_ , input_labels=lowercase_ , input_boxes=lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = self._normalize_and_convert( lowercase_ , lowercase_ , input_points=lowercase_ , input_labels=lowercase_ , input_boxes=lowercase_ , return_tensors=lowercase_ , ) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Tuple=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : str="pt" , ): '''simple docstring''' if input_points is not None: if len(lowercase_) != len(lowercase_): SCREAMING_SNAKE_CASE_ : List[str] = [ self._normalize_coordinates(self.target_size , lowercase_ , original_sizes[0]) for point in input_points ] else: SCREAMING_SNAKE_CASE_ : Any = [ self._normalize_coordinates(self.target_size , lowercase_ , lowercase_) for point, original_size in zip(lowercase_ , lowercase_) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points): if input_labels is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = self._pad_points_and_labels(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = np.array(lowercase_) if input_labels is not None: SCREAMING_SNAKE_CASE_ : int = np.array(lowercase_) if input_boxes is not None: if len(lowercase_) != len(lowercase_): SCREAMING_SNAKE_CASE_ : Any = [ self._normalize_coordinates(self.target_size , lowercase_ , original_sizes[0] , is_bounding_box=lowercase_) for box in input_boxes ] else: SCREAMING_SNAKE_CASE_ : Optional[Any] = [ self._normalize_coordinates(self.target_size , lowercase_ , lowercase_ , is_bounding_box=lowercase_) for box, original_size in zip(lowercase_ , lowercase_) ] SCREAMING_SNAKE_CASE_ : Any = np.array(lowercase_) if input_boxes is not None: if return_tensors == "pt": SCREAMING_SNAKE_CASE_ : int = torch.from_numpy(lowercase_) # boxes batch size of 1 by default SCREAMING_SNAKE_CASE_ : List[Any] = input_boxes.unsqueeze(1) if len(input_boxes.shape) != 3 else input_boxes elif return_tensors == "tf": SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase_) # boxes batch size of 1 by default SCREAMING_SNAKE_CASE_ : List[str] = tf.expand_dims(lowercase_ , 1) if len(input_boxes.shape) != 3 else input_boxes encoding_image_processor.update({'''input_boxes''': input_boxes}) if input_points is not None: if return_tensors == "pt": SCREAMING_SNAKE_CASE_ : int = torch.from_numpy(lowercase_) # point batch size of 1 by default SCREAMING_SNAKE_CASE_ : Dict = input_points.unsqueeze(1) if len(input_points.shape) != 4 else input_points elif return_tensors == "tf": SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.convert_to_tensor(lowercase_) # point batch size of 1 by default SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(lowercase_ , 1) if len(input_points.shape) != 4 else input_points encoding_image_processor.update({'''input_points''': input_points}) if input_labels is not None: if return_tensors == "pt": SCREAMING_SNAKE_CASE_ : Tuple = torch.from_numpy(lowercase_) # point batch size of 1 by default SCREAMING_SNAKE_CASE_ : Optional[int] = input_labels.unsqueeze(1) if len(input_labels.shape) != 3 else input_labels elif return_tensors == "tf": SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.convert_to_tensor(lowercase_) # point batch size of 1 by default SCREAMING_SNAKE_CASE_ : Optional[int] = tf.expand_dims(lowercase_ , 1) if len(input_labels.shape) != 3 else input_labels encoding_image_processor.update({'''input_labels''': input_labels}) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Optional[Any] , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = max([point.shape[0] for point in input_points]) SCREAMING_SNAKE_CASE_ : Any = [] for i, point in enumerate(lowercase_): if point.shape[0] != expected_nb_points: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2)) + self.point_pad_value] , axis=0) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.append(input_labels[i] , [self.point_pad_value]) processed_input_points.append(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = processed_input_points return input_points, input_labels def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : int , lowercase_ : np.ndarray , lowercase_ : Union[str, Any] , lowercase_ : Any=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = original_size SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.image_processor._get_preprocess_shape(lowercase_ , longest_edge=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = deepcopy(lowercase_).astype(lowercase_) if is_bounding_box: SCREAMING_SNAKE_CASE_ : Dict = coords.reshape(-1 , 2 , 2) SCREAMING_SNAKE_CASE_ : Tuple = coords[..., 0] * (new_w / old_w) SCREAMING_SNAKE_CASE_ : Tuple = coords[..., 1] * (new_h / old_h) if is_bounding_box: SCREAMING_SNAKE_CASE_ : Dict = coords.reshape(-1 , 4) return coords def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple=None , lowercase_ : Union[str, Any]=None , ): '''simple docstring''' if input_points is not None: if hasattr(lowercase_ , '''numpy'''): # Checks for TF or Torch tensor SCREAMING_SNAKE_CASE_ : str = input_points.numpy().tolist() if not isinstance(lowercase_ , lowercase_) or not isinstance(input_points[0] , lowercase_): raise ValueError('''Input points must be a list of list of floating points.''') SCREAMING_SNAKE_CASE_ : Tuple = [np.array(lowercase_) for input_point in input_points] else: SCREAMING_SNAKE_CASE_ : Any = None if input_labels is not None: if hasattr(lowercase_ , '''numpy'''): SCREAMING_SNAKE_CASE_ : int = input_labels.numpy().tolist() if not isinstance(lowercase_ , lowercase_) or not isinstance(input_labels[0] , lowercase_): raise ValueError('''Input labels must be a list of list integers.''') SCREAMING_SNAKE_CASE_ : Any = [np.array(lowercase_) for label in input_labels] else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None if input_boxes is not None: if hasattr(lowercase_ , '''numpy'''): SCREAMING_SNAKE_CASE_ : Any = input_boxes.numpy().tolist() if ( not isinstance(lowercase_ , lowercase_) or not isinstance(input_boxes[0] , lowercase_) or not isinstance(input_boxes[0][0] , lowercase_) ): raise ValueError('''Input boxes must be a list of list of list of floating points.''') SCREAMING_SNAKE_CASE_ : List[Any] = [np.array(lowercase_).astype(np.floataa) for box in input_boxes] else: SCREAMING_SNAKE_CASE_ : List[Any] = None return input_points, input_labels, input_boxes @property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' return self.image_processor.post_process_masks(*lowercase_ , **lowercase_)
91
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase_ : Optional[Any] = { """configuration_tapas""": ["""TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TapasConfig"""], """tokenization_tapas""": ["""TapasTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ """TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TapasForMaskedLM""", """TapasForQuestionAnswering""", """TapasForSequenceClassification""", """TapasModel""", """TapasPreTrainedModel""", """load_tf_weights_in_tapas""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ """TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFTapasForMaskedLM""", """TFTapasForQuestionAnswering""", """TFTapasForSequenceClassification""", """TFTapasModel""", """TFTapasPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys UpperCAmelCase_ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
1
"""simple docstring""" import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument UpperCAmelCase_ : str = { """/attention/""": """/0/SelfAttention/""", """/self_attention/""": """/0/SelfAttention/""", """/encoder_decoder_attention/""": """/1/EncDecAttention/""", """value""": """v""", """query""": """q""", """key""": """k""", """out""": """o""", """pre_self_attention_layer_norm""": """0/layer_norm""", """pre_cross_attention_layer_norm""": """1/layer_norm""", """pre_attention_layer_norm""": """0/layer_norm""", # previously 1, but seems wrong """token_embedder""": """shared""", """encoder_norm""": """final_layer_norm""", """decoder_norm""": """final_layer_norm""", """relpos_bias/rel_embedding""": """block/0/layer/0/SelfAttention/relative_attention_bias/weight""", """router/router_weights/w/""": """router/classifier/""", """roer/roer_weights/w/""": """router/classifier/""", """logits_dense""": """lm_head""", } def _A (__a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = list(s_dict.keys() ) for key in keys: SCREAMING_SNAKE_CASE_ : Tuple = R'''.*/layers_(\d+)''' SCREAMING_SNAKE_CASE_ : Optional[Any] = key if re.match(__a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = re.sub(R'''layers_(\d+)''' , R'''block/\1/layer''' , __a ) SCREAMING_SNAKE_CASE_ : Optional[int] = R'''(encoder|decoder)\/''' if re.match(__a , __a ): SCREAMING_SNAKE_CASE_ : Optional[Any] = re.match(__a , __a ).groups() if groups[0] == "encoder": SCREAMING_SNAKE_CASE_ : Optional[int] = re.sub(R'''/mlp/''' , R'''/1/mlp/''' , __a ) SCREAMING_SNAKE_CASE_ : Optional[int] = re.sub(R'''/pre_mlp_layer_norm/''' , R'''/1/layer_norm/''' , __a ) elif groups[0] == "decoder": SCREAMING_SNAKE_CASE_ : Optional[Any] = re.sub(R'''/mlp/''' , R'''/2/mlp/''' , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = re.sub(R'''/pre_mlp_layer_norm/''' , R'''/2/layer_norm/''' , __a ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: SCREAMING_SNAKE_CASE_ : Optional[int] = new_key.replace(__a , __a ) print(f'{key} -> {new_key}' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = s_dict.pop(__a ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: SCREAMING_SNAKE_CASE_ : Optional[int] = s_dict[ '''encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: SCREAMING_SNAKE_CASE_ : List[Any] = s_dict[ '''decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: SCREAMING_SNAKE_CASE_ : Any = s_dict[key].shape[0] SCREAMING_SNAKE_CASE_ : Any = s_dict[key] for idx in range(__a ): SCREAMING_SNAKE_CASE_ : str = expert_weihts[idx] print(f'{key} -> {key.replace("expert/" , "nested fstring" )}' ) s_dict.pop(__a ) return s_dict UpperCAmelCase_ : Tuple = { """NUM_ENCODER_LAYERS""": """num_layers""", """NUM_DECODER_LAYERS""": """num_decoder_layers""", """NUM_HEADS""": """num_heads""", """HEAD_DIM""": """d_kv""", """EMBED_DIM""": """d_model""", """MLP_DIM""": """d_ff""", """NUM_SELECTED_EXPERTS""": """num_selected_experts""", """NUM_ENCODER_SPARSE_LAYERS""": """num_sparse_encoder_layers""", """NUM_DECODER_SPARSE_LAYERS""": """num_sparse_decoder_layers""", """dense.MlpBlock.activations""": """feed_forward_proj""", } def _A (__a , __a ) -> List[Any]: """simple docstring""" import regex as re with open(__a , '''r''' ) as f: SCREAMING_SNAKE_CASE_ : List[Any] = f.read() SCREAMING_SNAKE_CASE_ : Any = re.findall(R'''(.*) = ([0-9.]*)''' , __a ) SCREAMING_SNAKE_CASE_ : Optional[int] = {} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": SCREAMING_SNAKE_CASE_ : Union[str, Any] = float(__a ) if '''.''' in value else int(__a ) SCREAMING_SNAKE_CASE_ : Dict = re.findall(R'''(.*activations) = \(\'(.*)\',\)''' , __a )[0] SCREAMING_SNAKE_CASE_ : Optional[int] = str(activation[1] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = num_experts SCREAMING_SNAKE_CASE_ : List[str] = SwitchTransformersConfig(**__a ) return config def _A (__a , __a , __a=None , __a="./" , __a=8 ) -> Union[str, Any]: """simple docstring""" print(f'Loading flax weights from : {flax_checkpoint_path}' ) SCREAMING_SNAKE_CASE_ : Optional[int] = checkpoints.load_tax_checkpoint(__a ) if gin_file is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = convert_gin_to_config(__a , __a ) else: SCREAMING_SNAKE_CASE_ : int = SwitchTransformersConfig.from_pretrained(__a ) SCREAMING_SNAKE_CASE_ : Dict = SwitchTransformersForConditionalGeneration(__a ) SCREAMING_SNAKE_CASE_ : Dict = flax_params['''target'''] SCREAMING_SNAKE_CASE_ : Any = flatten_dict(__a , sep='''/''' ) SCREAMING_SNAKE_CASE_ : List[Any] = rename_keys(__a ) SCREAMING_SNAKE_CASE_ : int = unflatten_dict(__a , sep='''/''' ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(__a , __a ) print(f'Save PyTorch model to {pytorch_dump_path}' ) pt_model.save_pretrained(__a ) if __name__ == "__main__": UpperCAmelCase_ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the""" """ model architecture. If not provided, a `gin_file` has to be provided.""" ), ) parser.add_argument( """--gin_file""", default=None, type=str, required=False, help="""Path to the gin config file. If not provided, a `config_file` has to be passed """, ) parser.add_argument( """--config_name""", default=None, type=str, required=False, help="""Config name of SwitchTransformers model.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output pytorch model.""" ) parser.add_argument("""--num_experts""", default=8, type=int, required=False, help="""Number of experts""") UpperCAmelCase_ : Any = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
91
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
1
"""simple docstring""" def _A (__a = 1_00 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = 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() = }''')
91
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : List[Any] = { """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""", # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "sew-d" def __init__( self : Dict , lowercase_ : Optional[Any]=32 , lowercase_ : List[Any]=768 , lowercase_ : int=12 , lowercase_ : Dict=12 , lowercase_ : Union[str, Any]=3072 , lowercase_ : Dict=2 , lowercase_ : List[Any]=512 , lowercase_ : Union[str, Any]=256 , lowercase_ : Optional[int]=True , lowercase_ : List[str]=True , lowercase_ : List[Any]=("p2c", "c2p") , lowercase_ : Optional[int]="layer_norm" , lowercase_ : List[Any]="gelu_python" , lowercase_ : int=0.1 , lowercase_ : Optional[int]=0.1 , lowercase_ : Optional[int]=0.1 , lowercase_ : List[str]=0.0 , lowercase_ : Any=0.1 , lowercase_ : Dict=0.02 , lowercase_ : str=1e-7 , lowercase_ : Optional[int]=1e-5 , lowercase_ : int="group" , lowercase_ : str="gelu" , lowercase_ : List[str]=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , lowercase_ : int=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , lowercase_ : List[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , lowercase_ : List[Any]=False , lowercase_ : int=128 , lowercase_ : List[Any]=16 , lowercase_ : Tuple=True , lowercase_ : Any=0.05 , lowercase_ : Tuple=10 , lowercase_ : List[str]=2 , lowercase_ : Any=0.0 , lowercase_ : int=10 , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[Any]="mean" , lowercase_ : List[Any]=False , lowercase_ : int=False , lowercase_ : str=256 , lowercase_ : int=0 , lowercase_ : str=1 , lowercase_ : Any=2 , **lowercase_ : Union[str, Any] , ): '''simple docstring''' super().__init__(**lowercase_ , pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = feat_extract_norm SCREAMING_SNAKE_CASE_ : Optional[Any] = feat_extract_activation SCREAMING_SNAKE_CASE_ : Optional[int] = list(lowercase_) SCREAMING_SNAKE_CASE_ : str = list(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = list(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = conv_bias SCREAMING_SNAKE_CASE_ : int = num_conv_pos_embeddings SCREAMING_SNAKE_CASE_ : Dict = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE_ : List[Any] = len(self.conv_dim) SCREAMING_SNAKE_CASE_ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = intermediate_size SCREAMING_SNAKE_CASE_ : int = squeeze_factor SCREAMING_SNAKE_CASE_ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE_ : Any = position_buckets SCREAMING_SNAKE_CASE_ : Tuple = share_att_key SCREAMING_SNAKE_CASE_ : Optional[int] = relative_attention SCREAMING_SNAKE_CASE_ : Tuple = norm_rel_ebd SCREAMING_SNAKE_CASE_ : Optional[int] = list(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : int = num_attention_heads SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout SCREAMING_SNAKE_CASE_ : List[str] = attention_dropout SCREAMING_SNAKE_CASE_ : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE_ : str = feat_proj_dropout SCREAMING_SNAKE_CASE_ : Optional[Any] = final_dropout SCREAMING_SNAKE_CASE_ : Any = layer_norm_eps SCREAMING_SNAKE_CASE_ : Optional[int] = feature_layer_norm_eps SCREAMING_SNAKE_CASE_ : Dict = initializer_range SCREAMING_SNAKE_CASE_ : Any = vocab_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect.''' '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,''' F'but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)' F'= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE_ : Optional[Any] = apply_spec_augment SCREAMING_SNAKE_CASE_ : Union[str, Any] = mask_time_prob SCREAMING_SNAKE_CASE_ : Dict = mask_time_length SCREAMING_SNAKE_CASE_ : Optional[Any] = mask_time_min_masks SCREAMING_SNAKE_CASE_ : List[Any] = mask_feature_prob SCREAMING_SNAKE_CASE_ : Tuple = mask_feature_length SCREAMING_SNAKE_CASE_ : Union[str, Any] = mask_feature_min_masks # ctc loss SCREAMING_SNAKE_CASE_ : int = ctc_loss_reduction SCREAMING_SNAKE_CASE_ : Any = ctc_zero_infinity # sequence classification SCREAMING_SNAKE_CASE_ : Optional[Any] = use_weighted_layer_sum SCREAMING_SNAKE_CASE_ : List[Any] = classifier_proj_size @property def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1)
91
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
1
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union UpperCAmelCase_ : List[str] = re.compile(r"""^(?P<major>\d+)""" r"""\.(?P<minor>\d+)""" r"""\.(?P<patch>\d+)$""") @total_ordering @dataclass class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = _str_to_version_tuple(self.version_str) def __repr__( self : Optional[Any]): '''simple docstring''' return F'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return self.major, self.minor, self.patch def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : List[Any]): '''simple docstring''' if isinstance(lowercase_ , lowercase_): return Version(lowercase_) elif isinstance(lowercase_ , lowercase_): return other raise TypeError(F'{other} (type {type(lowercase_)}) cannot be compared to version.') def __eq__( self : str , lowercase_ : Optional[Any]): '''simple docstring''' try: SCREAMING_SNAKE_CASE_ : List[str] = self._validate_operand(lowercase_) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : Dict , lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self._validate_operand(lowercase_) return self.tuple < other.tuple def __hash__( self : List[Any]): '''simple docstring''' return hash(_version_tuple_to_str(self.tuple)) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = {f.name for f in dataclasses.fields(cls)} return cls(**{k: v for k, v in dic.items() if k in field_names}) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return self.version_str def _A (__a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = _VERSION_REG.match(__a ) if not res: raise ValueError(f'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(__a ) for v in [res.group('''major''' ), res.group('''minor''' ), res.group('''patch''' )] ) def _A (__a ) -> List[str]: """simple docstring""" return ".".join(str(__a ) for v in version_tuple )
91
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (DDIMParallelScheduler,) __UpperCamelCase = (("eta", 0.0), ("num_inference_steps", 5_0)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : str = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = 10, 0.0 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Any = scheduler.step(lowercase_ , lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[Any] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(5) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1])) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' self.check_over_configs(thresholding=lowercase_) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=lowercase_ , prediction_type=lowercase_ , sample_max_value=lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for t in [1, 10, 49]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500]): self.check_over_forward(time_step=lowercase_ , num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0]): self.check_over_forward(time_step=lowercase_ , eta=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0) - 0.0)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400) - 0.1_47_71)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960) - 0.3_24_60)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0) - 0.0)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486) - 0.0_09_79)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998) - 0.02)) < 1e-5 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = 10, 0.0 scheduler.set_timesteps(lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.dummy_model() SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample_deter SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample_deter + 0.1 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample_deter - 0.1 SCREAMING_SNAKE_CASE_ : Dict = samplea.shape[0] SCREAMING_SNAKE_CASE_ : Optional[int] = torch.stack([samplea, samplea, samplea] , dim=0) SCREAMING_SNAKE_CASE_ : List[Any] = torch.arange(lowercase_)[0:3, None].repeat(1 , lowercase_) SCREAMING_SNAKE_CASE_ : str = model(samples.flatten(0 , 1) , timesteps.flatten(0 , 1)) SCREAMING_SNAKE_CASE_ : Any = scheduler.batch_step_no_noise(lowercase_ , timesteps.flatten(0 , 1) , samples.flatten(0 , 1) , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : int = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 11_47.79_04) < 1e-2 assert abs(result_mean.item() - 0.49_82) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop() SCREAMING_SNAKE_CASE_ : Dict = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : int = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_72.00_67) < 1e-2 assert abs(result_mean.item() - 0.22_39_67) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : Dict = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 52.53_02) < 1e-2 assert abs(result_mean.item() - 0.06_84) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : List[str] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : int = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_49.82_95) < 1e-2 assert abs(result_mean.item() - 0.19_51) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_49.07_84) < 1e-2 assert abs(result_mean.item() - 0.19_41) < 1e-3
91
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
1
"""simple docstring""" from __future__ import annotations from collections.abc import MutableSequence class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[str] , lowercase_ : int , lowercase_ : MutableSequence[float]): '''simple docstring''' if len(lowercase_) != degree + 1: raise ValueError( '''The number of coefficients should be equal to the degree + 1.''') SCREAMING_SNAKE_CASE_ : list[float] = list(lowercase_) SCREAMING_SNAKE_CASE_ : str = degree def __add__( self : int , lowercase_ : Polynomial): '''simple docstring''' if self.degree > polynomial_a.degree: SCREAMING_SNAKE_CASE_ : List[str] = self.coefficients[:] for i in range(polynomial_a.degree + 1): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree , lowercase_) else: SCREAMING_SNAKE_CASE_ : int = polynomial_a.coefficients[:] for i in range(self.degree + 1): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree , lowercase_) def __sub__( self : str , lowercase_ : Polynomial): '''simple docstring''' return self + polynomial_a * Polynomial(0 , [-1]) def __neg__( self : str): '''simple docstring''' return Polynomial(self.degree , [-c for c in self.coefficients]) def __mul__( self : List[Any] , lowercase_ : Polynomial): '''simple docstring''' SCREAMING_SNAKE_CASE_ : list[float] = [0] * (self.degree + polynomial_a.degree + 1) for i in range(self.degree + 1): for j in range(polynomial_a.degree + 1): coefficients[i + j] += ( self.coefficients[i] * polynomial_a.coefficients[j] ) return Polynomial(self.degree + polynomial_a.degree , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : int | float): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int | float = 0 for i in range(self.degree + 1): result += self.coefficients[i] * (substitution**i) return result def __str__( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for i in range(self.degree , -1 , -1): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i])) elif i == 1: polynomial += str(abs(self.coefficients[i])) + "x" else: polynomial += str(abs(self.coefficients[i])) + "x^" + str(lowercase_) return polynomial def __repr__( self : Tuple): '''simple docstring''' return self.__str__() def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : list[float] = [0] * self.degree for i in range(self.degree): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : int | float = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : list[float] = [0] * (self.degree + 2) SCREAMING_SNAKE_CASE_ : Any = constant for i in range(self.degree + 1): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 , lowercase_) def __eq__( self : str , lowercase_ : object): '''simple docstring''' if not isinstance(lowercase_ , lowercase_): return False if self.degree != polynomial_a.degree: return False for i in range(self.degree + 1): if self.coefficients[i] != polynomial_a.coefficients[i]: return False return True def __ne__( self : Union[str, Any] , lowercase_ : object): '''simple docstring''' return not self.__eq__(lowercase_)
91
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ShapEPipeline __UpperCamelCase = ["prompt"] __UpperCamelCase = ["prompt"] __UpperCamelCase = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] __UpperCamelCase = False @property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return 32 @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return 32 @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return self.time_input_dim * 4 @property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return 8 @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') return tokenizer @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(lowercase_) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } SCREAMING_SNAKE_CASE_ : Optional[Any] = PriorTransformer(**lowercase_) return model @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } SCREAMING_SNAKE_CASE_ : Optional[Any] = ShapERenderer(**lowercase_) return model def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.dummy_prior SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE_ : Any = self.dummy_tokenizer SCREAMING_SNAKE_CASE_ : int = self.dummy_renderer SCREAMING_SNAKE_CASE_ : str = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1024 , prediction_type='''sample''' , use_karras_sigmas=lowercase_ , clip_sample=lowercase_ , clip_sample_range=1.0 , ) SCREAMING_SNAKE_CASE_ : str = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int=0): '''simple docstring''' if str(lowercase_).startswith('''mps'''): SCREAMING_SNAKE_CASE_ : str = torch.manual_seed(lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = torch.Generator(device=lowercase_).manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : Any = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = '''cpu''' SCREAMING_SNAKE_CASE_ : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : List[str] = 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_ : List[str] = output.images[0] SCREAMING_SNAKE_CASE_ : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2]) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = torch_device == '''cpu''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=lowercase_ , relax_max_difference=lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : Optional[int] = self.pipeline_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = 1 SCREAMING_SNAKE_CASE_ : Optional[int] = 2 SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs(lowercase_) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE_ : List[str] = batch_size * [inputs[key]] SCREAMING_SNAKE_CASE_ : str = pipe(**lowercase_ , num_images_per_prompt=lowercase_)[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''') SCREAMING_SNAKE_CASE_ : int = ShapEPipeline.from_pretrained('''openai/shap-e''') SCREAMING_SNAKE_CASE_ : Optional[int] = pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = torch.Generator(device=lowercase_).manual_seed(0) SCREAMING_SNAKE_CASE_ : Any = pipe( '''a shark''' , generator=lowercase_ , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(lowercase_ , lowercase_)
91
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
1
"""simple docstring""" import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[str] , lowercase_ : Union[str, Any] , lowercase_ : Tuple=3 , lowercase_ : Union[str, Any]=32 , lowercase_ : Optional[Any]=3 , lowercase_ : Tuple=10 , lowercase_ : Dict=[8, 16, 32, 64] , lowercase_ : List[Any]=[1, 1, 2, 1] , lowercase_ : int=True , lowercase_ : Any=True , lowercase_ : List[str]="relu" , lowercase_ : Dict=3 , lowercase_ : List[str]=None , lowercase_ : Dict=["stage2", "stage3", "stage4"] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Any=1 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[str] = batch_size SCREAMING_SNAKE_CASE_ : List[Any] = image_size SCREAMING_SNAKE_CASE_ : Tuple = num_channels SCREAMING_SNAKE_CASE_ : List[str] = embeddings_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_sizes SCREAMING_SNAKE_CASE_ : str = depths SCREAMING_SNAKE_CASE_ : List[str] = is_training SCREAMING_SNAKE_CASE_ : List[str] = use_labels SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : List[Any] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = scope SCREAMING_SNAKE_CASE_ : List[str] = len(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = out_features SCREAMING_SNAKE_CASE_ : Tuple = out_indices SCREAMING_SNAKE_CASE_ : str = num_groups def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : str = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : str = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase_) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = BitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = BitBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[str] = model(lowercase_) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[1], 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:]) # verify backbone works with out_features=None SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : str = BitBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Any = model(lowercase_) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () __UpperCamelCase = ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = BitModelTester(self) SCREAMING_SNAKE_CASE_ : Tuple = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return @unittest.skip(reason='''Bit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' pass @unittest.skip(reason='''Bit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' pass @unittest.skip(reason='''Bit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Any = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Dict = model_class(config=lowercase_) for name, module in model.named_modules(): if isinstance(lowercase_ , (nn.BatchNormad, nn.GroupNorm)): self.assertTrue( torch.all(module.weight == 1) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) self.assertTrue( torch.all(module.bias == 0) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' def check_hidden_states_output(lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[str]): SCREAMING_SNAKE_CASE_ : Optional[int] = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.num_stages self.assertEqual(len(lowercase_) , expected_num_stages + 1) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Any = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_type SCREAMING_SNAKE_CASE_ : str = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Union[str, Any] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip(reason='''Bit does not use feedforward chunking''') def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Dict = BitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(lowercase_) SCREAMING_SNAKE_CASE_ : str = self.default_image_processor SCREAMING_SNAKE_CASE_ : Dict = prepare_img() SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : str = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : int = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[-0.65_26, -0.52_63, -1.43_98]]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4)) @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (BitBackbone,) if is_torch_available() else () __UpperCamelCase = BitConfig __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = BitModelTester(self)
91
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''') if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''') if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
1
"""simple docstring""" from __future__ import annotations from typing import Any class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Union[str, Any] , lowercase_ : int , lowercase_ : int , lowercase_ : float = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = row, column SCREAMING_SNAKE_CASE_ : Any = [[default_value for c in range(lowercase_)] for r in range(lowercase_)] def __str__( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = F'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier SCREAMING_SNAKE_CASE_ : List[str] = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE_ : str = max(lowercase_ , len(str(lowercase_))) SCREAMING_SNAKE_CASE_ : str = F'%{max_element_length}s' # Make string and return def single_line(lowercase_ : list[float]) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE_ : Any = '''[''' line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(lowercase_) for row_vector in self.array) return s def __repr__( self : str): '''simple docstring''' return str(self) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : tuple[int, int]): '''simple docstring''' if not (isinstance(lowercase_ , (list, tuple)) and len(lowercase_) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[int] , lowercase_ : tuple[int, int]): '''simple docstring''' assert self.validate_indicies(lowercase_) return self.array[loc[0]][loc[1]] def __setitem__( self : List[str] , lowercase_ : tuple[int, int] , lowercase_ : float): '''simple docstring''' assert self.validate_indicies(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = value def __add__( self : List[Any] , lowercase_ : Matrix): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE_ : str = Matrix(self.row , self.column) for r in range(self.row): for c in range(self.column): SCREAMING_SNAKE_CASE_ : Dict = self[r, c] + another[r, c] return result def __neg__( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = Matrix(self.row , self.column) for r in range(self.row): for c in range(self.column): SCREAMING_SNAKE_CASE_ : Optional[int] = -self[r, c] return result def __sub__( self : Dict , lowercase_ : Matrix): '''simple docstring''' return self + (-another) def __mul__( self : Tuple , lowercase_ : int | float | Matrix): '''simple docstring''' if isinstance(lowercase_ , (int, float)): # Scalar multiplication SCREAMING_SNAKE_CASE_ : Union[str, Any] = Matrix(self.row , self.column) for r in range(self.row): for c in range(self.column): SCREAMING_SNAKE_CASE_ : Optional[Any] = self[r, c] * another return result elif isinstance(lowercase_ , lowercase_): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE_ : Tuple = Matrix(self.row , another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE_ : str = F'Unsupported type given for another ({type(lowercase_)})' raise TypeError(lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = Matrix(self.column , self.row) for r in range(self.row): for c in range(self.column): SCREAMING_SNAKE_CASE_ : Optional[Any] = self[r, c] return result def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Matrix , lowercase_ : Matrix): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE_ : Union[str, Any] = v.transpose() SCREAMING_SNAKE_CASE_ : Optional[int] = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def _A () -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 print(f'a^(-1) is {ainv}' ) # u, v SCREAMING_SNAKE_CASE_ : Optional[Any] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = 1, 2, -3 SCREAMING_SNAKE_CASE_ : str = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = 4, -2, 5 print(f'u is {u}' ) print(f'v is {v}' ) print(f'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(f'(a + uv^T)^(-1) is {ainv.sherman_morrison(__a , __a )}' ) def _A () -> None: """simple docstring""" import doctest doctest.testmod() testa()
91
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
1
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase_ : Dict = { """vocab_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase_ : Tuple = { """vocab_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase_ : Optional[Any] = { """facebook/dpr-ctx_encoder-single-nq-base""": 512, """facebook/dpr-ctx_encoder-multiset-base""": 512, } UpperCAmelCase_ : Any = { """facebook/dpr-question_encoder-single-nq-base""": 512, """facebook/dpr-question_encoder-multiset-base""": 512, } UpperCAmelCase_ : List[Any] = { """facebook/dpr-reader-single-nq-base""": 512, """facebook/dpr-reader-multiset-base""": 512, } UpperCAmelCase_ : Tuple = { """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True}, } UpperCAmelCase_ : Tuple = { """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True}, } UpperCAmelCase_ : int = { """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True}, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = DPRContextEncoderTokenizer class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = DPRQuestionEncoderTokenizer UpperCAmelCase_ : List[str] = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) UpperCAmelCase_ : Dict = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) UpperCAmelCase_ : List[Any] = r""" Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. """ @add_start_docstrings(UpperCAmelCase__ ) class lowerCAmelCase__ : '''simple docstring''' def __call__( self : List[Any] , lowercase_ : List[str] , lowercase_ : Optional[str] = None , lowercase_ : Optional[str] = None , lowercase_ : Union[bool, str] = False , lowercase_ : Union[bool, str] = False , lowercase_ : Optional[int] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : Optional[bool] = None , **lowercase_ : Optional[Any] , ): '''simple docstring''' if titles is None and texts is None: return super().__call__( lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , return_tensors=lowercase_ , return_attention_mask=lowercase_ , **lowercase_ , ) elif titles is None or texts is None: SCREAMING_SNAKE_CASE_ : List[Any] = titles if texts is None else texts return super().__call__( lowercase_ , lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , return_tensors=lowercase_ , return_attention_mask=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = titles if not isinstance(lowercase_ , lowercase_) else [titles] SCREAMING_SNAKE_CASE_ : Union[str, Any] = texts if not isinstance(lowercase_ , lowercase_) else [texts] SCREAMING_SNAKE_CASE_ : Any = len(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = questions if not isinstance(lowercase_ , lowercase_) else [questions] * n_passages assert len(lowercase_) == len( lowercase_), F'There should be as many titles than texts but got {len(lowercase_)} titles and {len(lowercase_)} texts.' SCREAMING_SNAKE_CASE_ : List[str] = super().__call__(lowercase_ , lowercase_ , padding=lowercase_ , truncation=lowercase_)['''input_ids'''] SCREAMING_SNAKE_CASE_ : Tuple = super().__call__(lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_)['''input_ids'''] SCREAMING_SNAKE_CASE_ : Dict = { '''input_ids''': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(lowercase_ , lowercase_) ] } if return_attention_mask is not False: SCREAMING_SNAKE_CASE_ : List[str] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids]) SCREAMING_SNAKE_CASE_ : int = attention_mask return self.pad(lowercase_ , padding=lowercase_ , max_length=lowercase_ , return_tensors=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : BatchEncoding , lowercase_ : DPRReaderOutput , lowercase_ : int = 16 , lowercase_ : int = 64 , lowercase_ : int = 4 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = reader_input['''input_ids'''] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = reader_output[:3] SCREAMING_SNAKE_CASE_ : List[Any] = len(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = sorted(range(lowercase_) , reverse=lowercase_ , key=relevance_logits.__getitem__) SCREAMING_SNAKE_CASE_ : List[DPRReaderOutput] = [] for doc_id in sorted_docs: SCREAMING_SNAKE_CASE_ : str = list(input_ids[doc_id]) # assuming question & title information is at the beginning of the sequence SCREAMING_SNAKE_CASE_ : Optional[int] = sequence_ids.index(self.sep_token_id , 2) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: SCREAMING_SNAKE_CASE_ : str = sequence_ids.index(self.pad_token_id) else: SCREAMING_SNAKE_CASE_ : List[str] = len(lowercase_) SCREAMING_SNAKE_CASE_ : int = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=lowercase_ , top_spans=lowercase_ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=lowercase_ , start_index=lowercase_ , end_index=lowercase_ , text=self.decode(sequence_ids[start_index : end_index + 1]) , )) if len(lowercase_) >= num_spans: break return nbest_spans_predictions[:num_spans] def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : List[int] , lowercase_ : List[int] , lowercase_ : int , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for start_index, start_score in enumerate(lowercase_): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]): scores.append(((start_index, start_index + answer_length), start_score + end_score)) SCREAMING_SNAKE_CASE_ : List[str] = sorted(lowercase_ , key=lambda lowercase_: x[1] , reverse=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'Wrong span indices: [{start_index}:{end_index}]' SCREAMING_SNAKE_CASE_ : List[str] = end_index - start_index + 1 assert length <= max_answer_length, F'Span is too long: {length} > {max_answer_length}' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals): continue chosen_span_intervals.append((start_index, end_index)) if len(lowercase_) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase__ ) class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = READER_PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = READER_PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DPRReaderTokenizer
91
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
1
"""simple docstring""" from pathlib import Path import numpy as np from PIL import Image def _A (__a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b def _A (__a ) -> np.ndarray: """simple docstring""" return (gray > 1_27) & (gray <= 2_55) def _A (__a , __a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = np.zeros_like(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE_ : Union[str, Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE_ : int = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE_ : Any = int(summation > 0 ) return output if __name__ == "__main__": # read original image UpperCAmelCase_ : Dict = Path(__file__).resolve().parent / """image_data""" / """lena.jpg""" UpperCAmelCase_ : int = np.array(Image.open(lena_path)) # kernel to be applied UpperCAmelCase_ : Union[str, Any] = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) UpperCAmelCase_ : Union[str, Any] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image UpperCAmelCase_ : List[Any] = Image.fromarray(output).convert("""RGB""") pil_img.save("""result_dilation.png""")
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : List[str] = [ """word_embeddings_layernorm.weight""", """word_embeddings_layernorm.bias""", """input_layernorm.weight""", """input_layernorm.bias""", """post_attention_layernorm.weight""", """post_attention_layernorm.bias""", """self_attention.dense.bias""", """mlp.dense_4h_to_h.bias""", """ln_f.weight""", """ln_f.bias""", ] UpperCAmelCase_ : List[Any] = [ """mlp.dense_4h_to_h.weight""", """self_attention.dense.weight""", ] def _A (__a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = { '''word_embeddings.weight''': '''word_embeddings.weight''', '''word_embeddings.norm.weight''': '''word_embeddings_layernorm.weight''', '''word_embeddings.norm.bias''': '''word_embeddings_layernorm.bias''', '''weight''': '''ln_f.weight''', '''bias''': '''ln_f.bias''', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks SCREAMING_SNAKE_CASE_ : Tuple = int(re.match(R'''.*layer_(\d*).*''' , __a )[1] ) layer_number -= 3 return f'h.{layer_number}.' + key def _A (__a ) -> int: """simple docstring""" if dtype == torch.bool: return 1 / 8 SCREAMING_SNAKE_CASE_ : Dict = re.search(R'''[^\d](\d+)$''' , str(__a ) ) if bit_search is None: raise ValueError(f'`dtype` is not a valid dtype: {dtype}.' ) SCREAMING_SNAKE_CASE_ : int = int(bit_search.groups()[0] ) return bit_size // 8 def _A (__a , __a , __a , __a , __a ) -> Optional[Any]: """simple docstring""" if bloom_config_file == "": SCREAMING_SNAKE_CASE_ : List[Any] = BloomConfig() else: SCREAMING_SNAKE_CASE_ : str = BloomConfig.from_json_file(__a ) if shard_model: SCREAMING_SNAKE_CASE_ : List[Any] = os.listdir(__a ) SCREAMING_SNAKE_CASE_ : List[str] = sorted(filter(lambda __a : s.startswith('''layer''' ) and "model_00" in s , __a ) ) SCREAMING_SNAKE_CASE_ : List[str] = {'''weight_map''': {}, '''metadata''': {}} SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Optional[int] = BloomConfig() for j, file in enumerate(__a ): print('''Processing file: {}'''.format(__a ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = None for i in range(__a ): # load all TP files SCREAMING_SNAKE_CASE_ : List[str] = file.replace('''model_00''' , f'model_0{i}' ) SCREAMING_SNAKE_CASE_ : Tuple = torch.load(os.path.join(__a , __a ) , map_location='''cpu''' ) # Rename keys in the transformers names SCREAMING_SNAKE_CASE_ : Optional[int] = list(temp.keys() ) for key in keys: SCREAMING_SNAKE_CASE_ : Dict = temp.pop(__a ) if tensors is None: SCREAMING_SNAKE_CASE_ : Any = temp else: for key in tensors.keys(): if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel SCREAMING_SNAKE_CASE_ : int = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks SCREAMING_SNAKE_CASE_ : Optional[int] = torch.cat([tensors[key], temp[key]] , dim=__a ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tensors[key] / pretraining_tp torch.save( __a , os.path.join( __a , '''pytorch_model_{}-of-{}.bin'''.format(str(j + 1 ).zfill(5 ) , str(len(__a ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: SCREAMING_SNAKE_CASE_ : str = '''pytorch_model_{}-of-{}.bin'''.format( str(j + 1 ).zfill(5 ) , str(len(__a ) ).zfill(5 ) ) SCREAMING_SNAKE_CASE_ : List[str] = BloomConfig() SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME SCREAMING_SNAKE_CASE_ : Dict = total_size with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) with open(os.path.join(__a , WEIGHTS_NAME + '''.index.json''' ) , '''w''' , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = json.dumps(__a , indent=2 , sort_keys=__a ) + '''\n''' f.write(__a ) else: SCREAMING_SNAKE_CASE_ : str = BloomModel(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = os.listdir(__a ) SCREAMING_SNAKE_CASE_ : int = sorted(filter(lambda __a : s.startswith('''layer''' ) and "model_00" in s , __a ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = None for i, file in enumerate(__a ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = None for i in range(__a ): # load all TP files SCREAMING_SNAKE_CASE_ : List[Any] = file.replace('''model_00''' , f'model_0{i}' ) SCREAMING_SNAKE_CASE_ : List[str] = torch.load(os.path.join(__a , __a ) , map_location='''cpu''' ) # Rename keys in the transformers names SCREAMING_SNAKE_CASE_ : str = list(temp.keys() ) for key in keys: SCREAMING_SNAKE_CASE_ : Optional[int] = temp.pop(__a ) if tensors is None: SCREAMING_SNAKE_CASE_ : List[str] = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel SCREAMING_SNAKE_CASE_ : List[Any] = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks SCREAMING_SNAKE_CASE_ : List[Any] = torch.cat([tensors[key], temp[key]] , dim=__a ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): SCREAMING_SNAKE_CASE_ : str = tensors[key] / pretraining_tp SCREAMING_SNAKE_CASE_ : Tuple = model.load_state_dict(__a , strict=__a ) assert not other_keys.unexpected_keys, f'The keys {other_keys.unexpected_keys} are unexpected' if missing_keys is None: SCREAMING_SNAKE_CASE_ : List[Any] = set(other_keys.missing_keys ) else: SCREAMING_SNAKE_CASE_ : Tuple = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, f'The keys {missing_keys} are missing' # Save pytorch-model os.makedirs(__a , exist_ok=__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : Optional[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}' ) if config.torch_dtype is not None: SCREAMING_SNAKE_CASE_ : List[str] = model.to(config.torch_dtype ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( """--bloom_checkpoint_path""", default=None, type=str, required=True, help="""Path to the Megatron-LM checkpoint path.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--bloom_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--shard_model""", action="""store_true""", help="""An optional setting to shard the output model \nThis enables sharding the converted checkpoint""", ) parser.add_argument( """--pretraining_tp""", default=4, type=int, help="""Pretraining TP rank that has been used when training the model in Megatron-LM \n""", ) UpperCAmelCase_ : List[Any] = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
91
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
1
"""simple docstring""" def _A (__a , __a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , __a ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Tuple = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(__a ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : List[str] = factorials.pop() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = divmod(__a , __a ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
91
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
1
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = None # Automatically constructed __UpperCamelCase = "dict" __UpperCamelCase = None __UpperCamelCase = field(default="Translation" , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def __call__( self : List[str]): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages)}) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' from .features import Value return {k: Value('''string''') for k in sorted(self.languages)} @dataclass class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None # Automatically constructed __UpperCamelCase = "dict" __UpperCamelCase = None __UpperCamelCase = field(default="TranslationVariableLanguages" , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = sorted(set(self.languages)) if self.languages else None SCREAMING_SNAKE_CASE_ : Any = len(self.languages) if self.languages else None def __call__( self : Optional[int]): '''simple docstring''' return pa.struct({'''language''': pa.list_(pa.string()), '''translation''': pa.list_(pa.string())}) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = set(self.languages) if self.languages and set(lowercase_) - lang_set: raise ValueError( F'Some languages in example ({", ".join(sorted(set(lowercase_) - lang_set))}) are not in valid set ({", ".join(lowercase_)}).') # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE_ : int = [] for lang, text in translation_dict.items(): if isinstance(lowercase_ , lowercase_): translation_tuples.append((lang, text)) else: translation_tuples.extend([(lang, el) for el in text]) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = zip(*sorted(lowercase_)) return {"language": languages, "translation": translations} def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value('''string''')), "translation": Sequence(Value('''string''')), }
91
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
1
"""simple docstring""" from ....utils import logging UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Dict , lowercase_ : str , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=2048): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = config.__dict__ SCREAMING_SNAKE_CASE_ : Any = modal_hidden_size if num_labels: SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels
91
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
1
"""simple docstring""" 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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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 # ######################################################################## UpperCAmelCase_ : Any = 16 UpperCAmelCase_ : List[str] = 32 def _A (__a , __a = 16 ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) SCREAMING_SNAKE_CASE_ : str = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ : Dict = 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(): SCREAMING_SNAKE_CASE_ : Dict = 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 SCREAMING_SNAKE_CASE_ : Tuple = 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. SCREAMING_SNAKE_CASE_ : Dict = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_ : Tuple = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_ : Optional[Any] = 8 else: SCREAMING_SNAKE_CASE_ : Any = None return tokenizer.pad( __a , padding='''longest''' , max_length=__a , pad_to_multiple_of=__a , return_tensors='''pt''' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ : List[Any] = DataLoader( tokenized_datasets['''train'''] , shuffle=__a , collate_fn=__a , batch_size=__a ) SCREAMING_SNAKE_CASE_ : List[Any] = 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 UpperCAmelCase_ : Union[str, Any] = mocked_dataloaders # noqa: F811 def _A (__a , __a ) -> Union[str, Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __a ) == "1": SCREAMING_SNAKE_CASE_ : Optional[int] = 2 # Initialize accelerator SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_ : str = config['''lr'''] SCREAMING_SNAKE_CASE_ : Any = int(config['''num_epochs'''] ) SCREAMING_SNAKE_CASE_ : str = int(config['''seed'''] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = int(config['''batch_size'''] ) SCREAMING_SNAKE_CASE_ : List[str] = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE_ : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE_ : Any = MAX_GPU_BATCH_SIZE set_seed(__a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = get_dataloaders(__a , __a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_ : Optional[int] = 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). SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_ : Tuple = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler SCREAMING_SNAKE_CASE_ : Dict = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=1_00 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # 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. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE_ : List[str] = model(**__a ) SCREAMING_SNAKE_CASE_ : str = outputs.loss SCREAMING_SNAKE_CASE_ : int = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() SCREAMING_SNAKE_CASE_ : Any = 0 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(): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(**__a ) SCREAMING_SNAKE_CASE_ : Tuple = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.gather((predictions, batch['''labels''']) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(__a ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples SCREAMING_SNAKE_CASE_ : Any = predictions[: len(eval_dataloader.dataset ) - samples_seen] SCREAMING_SNAKE_CASE_ : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=__a , references=__a , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' , __a ) def _A () -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = 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.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) SCREAMING_SNAKE_CASE_ : int = parser.parse_args() SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__a , __a ) if __name__ == "__main__": main()
91
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is None: return [1] + ([0] * len(lowercase_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
1
"""simple docstring""" import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline UpperCAmelCase_ : Optional[int] = { """n_samples""": 64, """horizon""": 32, """num_inference_steps""": 20, """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_ : str = """hopper-medium-v2""" UpperCAmelCase_ : int = gym.make(env_name) UpperCAmelCase_ : Any = ValueGuidedRLPipeline.from_pretrained( """bglick13/hopper-medium-v2-value-function-hor32""", env=env, ) env.seed(0) UpperCAmelCase_ : Optional[int] = env.reset() UpperCAmelCase_ : str = 0 UpperCAmelCase_ : List[Any] = 0 UpperCAmelCase_ : List[str] = 1000 UpperCAmelCase_ : List[str] = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy UpperCAmelCase_ : Dict = pipeline(obs, planning_horizon=32) # execute action in environment UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = env.step(denorm_actions) UpperCAmelCase_ : Union[str, Any] = 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_ : int = next_observation except KeyboardInterrupt: pass print(f'''Total reward: {total_reward}''')
91
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : str = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_))
91
1
"""simple docstring""" import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model UpperCAmelCase_ : str = """0.12""" # assumed parallelism: 8 if is_torch_available(): import torch def _A (__a , __a , __a=None ) -> str: """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE_ : Any = random.Random() SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 for dim in shape: total_dims *= dim SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for _ in range(__a ): values.append(rng.randint(0 , vocab_size - 1 ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = np.array(__a , dtype=jnp.intaa ).reshape(__a ) return output def _A (__a , __a=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor(__a , vocab_size=2 , rng=__a ) # make sure that at least one token is attended to for each batch SCREAMING_SNAKE_CASE_ : str = 1 return attn_mask @require_flax class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = None __UpperCamelCase = () def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 SCREAMING_SNAKE_CASE_ : List[Any] = 2 SCREAMING_SNAKE_CASE_ : Tuple = inputs['''input_ids'''].shape[-1] // 2 SCREAMING_SNAKE_CASE_ : Tuple = inputs['''input_ids'''][:max_batch_size, :sequence_length] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.ones_like(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens SCREAMING_SNAKE_CASE_ : Union[str, Any] = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` SCREAMING_SNAKE_CASE_ : Any = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : Tuple = False SCREAMING_SNAKE_CASE_ : int = max_length SCREAMING_SNAKE_CASE_ : str = 0 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : int = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE_ : List[str] = getattr(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = pt_model_class(lowercase_).eval() SCREAMING_SNAKE_CASE_ : int = load_flax_weights_in_pytorch_model(lowercase_ , flax_model.params) SCREAMING_SNAKE_CASE_ : Tuple = flax_model.generate(lowercase_).sequences SCREAMING_SNAKE_CASE_ : Dict = pt_model.generate(torch.tensor(lowercase_ , dtype=torch.long)) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: SCREAMING_SNAKE_CASE_ : int = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : Any = False SCREAMING_SNAKE_CASE_ : Optional[Any] = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = model.generate(lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Any = jit(model.generate) SCREAMING_SNAKE_CASE_ : Optional[int] = jit_generate(lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : Any = True SCREAMING_SNAKE_CASE_ : List[Any] = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : List[Any] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = model.generate(lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = jit(model.generate) SCREAMING_SNAKE_CASE_ : Any = jit_generate(lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : Dict = False SCREAMING_SNAKE_CASE_ : int = max_length SCREAMING_SNAKE_CASE_ : Tuple = 2 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Any = model.generate(lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = jit(model.generate) SCREAMING_SNAKE_CASE_ : Tuple = jit_generate(lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : Optional[Any] = max_length SCREAMING_SNAKE_CASE_ : str = 2 SCREAMING_SNAKE_CASE_ : Optional[Any] = 2 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : List[Any] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : int = model.generate(lowercase_).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : str = max_length SCREAMING_SNAKE_CASE_ : Tuple = 0.8 SCREAMING_SNAKE_CASE_ : Tuple = 10 SCREAMING_SNAKE_CASE_ : Optional[int] = 0.3 SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : Tuple = 8 SCREAMING_SNAKE_CASE_ : Optional[Any] = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : Tuple = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.generate(lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = jit(model.generate) SCREAMING_SNAKE_CASE_ : List[Any] = jit_generate(lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : Any = max_length SCREAMING_SNAKE_CASE_ : List[Any] = 1 SCREAMING_SNAKE_CASE_ : Optional[int] = 8 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : int = model.generate(lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = jit(model.generate) SCREAMING_SNAKE_CASE_ : Union[str, Any] = jit_generate(lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE_ : int = max_length SCREAMING_SNAKE_CASE_ : List[Any] = 2 SCREAMING_SNAKE_CASE_ : Tuple = 1 SCREAMING_SNAKE_CASE_ : Dict = 8 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model.generate(lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = jit(model.generate) SCREAMING_SNAKE_CASE_ : Dict = jit_generate(lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE_ : str = attention_mask.at[(0, 0)].set(0) SCREAMING_SNAKE_CASE_ : Dict = False SCREAMING_SNAKE_CASE_ : Tuple = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = model.generate(lowercase_ , attention_mask=lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = jit(model.generate) SCREAMING_SNAKE_CASE_ : List[Any] = jit_generate(lowercase_ , attention_mask=lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE_ : List[Any] = attention_mask.at[(0, 0)].set(0) SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : List[Any] = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = model.generate(lowercase_ , attention_mask=lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = jit(model.generate) SCREAMING_SNAKE_CASE_ : int = jit_generate(lowercase_ , attention_mask=lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE_ : Any = attention_mask.at[(0, 0)].set(0) SCREAMING_SNAKE_CASE_ : Dict = 2 SCREAMING_SNAKE_CASE_ : Any = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = model.generate(lowercase_ , attention_mask=lowercase_).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = jit(model.generate) SCREAMING_SNAKE_CASE_ : Optional[Any] = jit_generate(lowercase_ , attention_mask=lowercase_).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist()) @require_flax class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert''') SCREAMING_SNAKE_CASE_ : Any = FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''') SCREAMING_SNAKE_CASE_ : List[str] = '''Hello world''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer(lowercase_ , return_tensors='''np''').input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(lowercase_ , '''do_samples'''): model.generate(lowercase_ , do_samples=lowercase_) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(lowercase_ , '''foo'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''foo''': '''bar'''} model.generate(lowercase_ , **lowercase_)
91
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase_ : str = { """configuration_mobilenet_v2""": [ """MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileNetV2Config""", """MobileNetV2OnnxConfig""", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = ["""MobileNetV2FeatureExtractor"""] UpperCAmelCase_ : Dict = ["""MobileNetV2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileNetV2ForImageClassification""", """MobileNetV2ForSemanticSegmentation""", """MobileNetV2Model""", """MobileNetV2PreTrainedModel""", """load_tf_weights_in_mobilenet_v2""", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys UpperCAmelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig UpperCAmelCase_ : Optional[int] = { """google/tapas-base-finetuned-sqa""": ( """https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json""" ), """google/tapas-base-finetuned-wtq""": ( """https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json""" ), """google/tapas-base-finetuned-wikisql-supervised""": ( """https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json""" ), """google/tapas-base-finetuned-tabfact""": ( """https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json""" ), } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "tapas" def __init__( self : List[str] , lowercase_ : Tuple=30522 , lowercase_ : str=768 , lowercase_ : List[str]=12 , lowercase_ : str=12 , lowercase_ : str=3072 , lowercase_ : str="gelu" , lowercase_ : Optional[int]=0.1 , lowercase_ : Union[str, Any]=0.1 , lowercase_ : Tuple=1024 , lowercase_ : Union[str, Any]=[3, 256, 256, 2, 256, 256, 10] , lowercase_ : Union[str, Any]=0.02 , lowercase_ : List[Any]=1e-12 , lowercase_ : Dict=0 , lowercase_ : Tuple=10.0 , lowercase_ : Optional[int]=0 , lowercase_ : Optional[int]=1.0 , lowercase_ : List[str]=None , lowercase_ : Optional[Any]=1.0 , lowercase_ : int=False , lowercase_ : Any=None , lowercase_ : List[Any]=1.0 , lowercase_ : List[Any]=1.0 , lowercase_ : Any=False , lowercase_ : Optional[int]=False , lowercase_ : Dict="ratio" , lowercase_ : Tuple=None , lowercase_ : Optional[int]=None , lowercase_ : List[str]=64 , lowercase_ : Tuple=32 , lowercase_ : Optional[int]=False , lowercase_ : int=True , lowercase_ : Any=False , lowercase_ : Optional[int]=False , lowercase_ : str=True , lowercase_ : Optional[Any]=False , lowercase_ : str=None , lowercase_ : str=None , **lowercase_ : List[str] , ): '''simple docstring''' super().__init__(pad_token_id=lowercase_ , **lowercase_) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) SCREAMING_SNAKE_CASE_ : Dict = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : str = num_attention_heads SCREAMING_SNAKE_CASE_ : List[Any] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_sizes SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps # Fine-tuning task hyperparameters SCREAMING_SNAKE_CASE_ : Dict = positive_label_weight SCREAMING_SNAKE_CASE_ : Dict = num_aggregation_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = aggregation_loss_weight SCREAMING_SNAKE_CASE_ : List[str] = use_answer_as_supervision SCREAMING_SNAKE_CASE_ : Tuple = answer_loss_importance SCREAMING_SNAKE_CASE_ : str = use_normalized_answer_loss SCREAMING_SNAKE_CASE_ : str = huber_loss_delta SCREAMING_SNAKE_CASE_ : List[str] = temperature SCREAMING_SNAKE_CASE_ : Optional[Any] = aggregation_temperature SCREAMING_SNAKE_CASE_ : Union[str, Any] = use_gumbel_for_cells SCREAMING_SNAKE_CASE_ : List[str] = use_gumbel_for_aggregation SCREAMING_SNAKE_CASE_ : Tuple = average_approximation_function SCREAMING_SNAKE_CASE_ : Any = cell_selection_preference SCREAMING_SNAKE_CASE_ : Tuple = answer_loss_cutoff SCREAMING_SNAKE_CASE_ : str = max_num_rows SCREAMING_SNAKE_CASE_ : Any = max_num_columns SCREAMING_SNAKE_CASE_ : int = average_logits_per_cell SCREAMING_SNAKE_CASE_ : Dict = select_one_column SCREAMING_SNAKE_CASE_ : Union[str, Any] = allow_empty_column_selection SCREAMING_SNAKE_CASE_ : int = init_cell_selection_weights_to_zero SCREAMING_SNAKE_CASE_ : Union[str, Any] = reset_position_index_per_cell SCREAMING_SNAKE_CASE_ : Union[str, Any] = disable_per_token_loss # Aggregation hyperparameters SCREAMING_SNAKE_CASE_ : List[str] = aggregation_labels SCREAMING_SNAKE_CASE_ : Any = no_aggregation_label_index if isinstance(self.aggregation_labels , lowercase_): SCREAMING_SNAKE_CASE_ : Dict = {int(lowercase_): v for k, v in aggregation_labels.items()}
91
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
1
"""simple docstring""" import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import ( SeqaSeqDataset, calculate_bleu, calculate_rouge, chunks, lmap, load_json, parse_numeric_n_bool_cl_kwargs, save_json, use_task_specific_params, write_txt_file, ) UpperCAmelCase_ : Tuple = getLogger(__name__) def _A (__a , __a , __a , __a = 8 , __a = 10_24 , __a="val" , __a=None , __a=False , __a="summarization" , __a=None , __a=1 , __a = None , __a="" , **__a , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(__a ) assert local_rank is not None torch.distributed.init_process_group(backend='''nccl''' , rank=__a ) SCREAMING_SNAKE_CASE_ : int = Path(__a ) SCREAMING_SNAKE_CASE_ : str = save_dir.joinpath(f'rank_{local_rank}_output.json' ) torch.cuda.set_device(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__a ).cuda() if fpaa: SCREAMING_SNAKE_CASE_ : List[Any] = model.half() # determine if we need to increase num_beams use_task_specific_params(__a , __a ) # update config with task specific params SCREAMING_SNAKE_CASE_ : str = generate_kwargs.pop('''num_beams''' , model.config.num_beams ) # AttributeError risk? if num_return_sequences > num_beams: SCREAMING_SNAKE_CASE_ : Tuple = num_return_sequences SCREAMING_SNAKE_CASE_ : Tuple = AutoTokenizer.from_pretrained(__a ) logger.info(f'Inferred tokenizer type: {tokenizer.__class__}' ) # if this is wrong, check config.model_type. if max_source_length is None: SCREAMING_SNAKE_CASE_ : int = tokenizer.model_max_length if prefix is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = SeqaSeqDataset( __a , __a , __a , max_target_length=10_24 , type_path=__a , n_obs=__a , prefix=__a , **__a , ) # I set shuffle=True for a more accurate progress bar. # If all the longest samples are first, the prog bar estimate is too high at the beginning. SCREAMING_SNAKE_CASE_ : str = ds.make_sortish_sampler(__a , distributed=__a , add_extra_examples=__a , shuffle=__a ) SCREAMING_SNAKE_CASE_ : int = DataLoader(__a , sampler=__a , batch_size=__a , collate_fn=ds.collate_fn ) SCREAMING_SNAKE_CASE_ : str = [] for batch in tqdm(__a ): SCREAMING_SNAKE_CASE_ : Dict = model.generate( input_ids=batch['''input_ids'''].to(model.device ) , attention_mask=batch['''attention_mask'''].to(model.device ) , num_return_sequences=__a , num_beams=__a , **__a , ) SCREAMING_SNAKE_CASE_ : int = tokenizer.batch_decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) SCREAMING_SNAKE_CASE_ : Tuple = batch['''ids'''] if num_return_sequences > 1: SCREAMING_SNAKE_CASE_ : Dict = chunks(__a , __a ) # batch size chunks, each of size num_return_seq for i, pred in enumerate(__a ): results.append({'''pred''': pred, '''id''': ids[i].item()} ) save_json(__a , __a ) return results, sampler.num_replicas def _A () -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = argparse.ArgumentParser( epilog='''Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate''' ) parser.add_argument('''--data_dir''' , type=__a , help='''like cnn_dm/test.source''' ) parser.add_argument( '''--model_name''' , type=__a , help='''like facebook/bart-large-cnn,t5-base, etc.''' , default='''sshleifer/distilbart-xsum-12-3''' , ) parser.add_argument('''--save_dir''' , type=__a , help='''where to save''' , default='''tmp_gen''' ) parser.add_argument('''--max_source_length''' , type=__a , default=__a ) parser.add_argument( '''--type_path''' , type=__a , default='''test''' , help='''which subset to evaluate typically train/val/test''' ) parser.add_argument('''--task''' , type=__a , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=__a , default=8 , required=__a , help='''batch size''' ) parser.add_argument( '''--local_rank''' , type=__a , default=-1 , required=__a , help='''should be passed by distributed.launch''' ) parser.add_argument( '''--n_obs''' , type=__a , default=__a , required=__a , help='''How many observations. Defaults to all.''' ) parser.add_argument( '''--num_return_sequences''' , type=__a , default=1 , required=__a , help='''How many sequences to return''' ) parser.add_argument( '''--sync_timeout''' , type=__a , default=6_00 , required=__a , help='''How long should master process wait for other processes to finish.''' , ) parser.add_argument('''--src_lang''' , type=__a , default=__a , required=__a ) parser.add_argument('''--tgt_lang''' , type=__a , default=__a , required=__a ) parser.add_argument( '''--prefix''' , type=__a , required=__a , default=__a , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--debug''' , action='''store_true''' ) SCREAMING_SNAKE_CASE_ : Any = time.time() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = parser.parse_known_args() SCREAMING_SNAKE_CASE_ : Optional[Any] = parse_numeric_n_bool_cl_kwargs(__a ) if generate_kwargs and args.local_rank <= 0: print(f'parsed the following generate kwargs: {generate_kwargs}' ) SCREAMING_SNAKE_CASE_ : Dict = Path(args.save_dir + '''_tmp''' ) Path(__a ).mkdir(exist_ok=__a ) # this handles locking. SCREAMING_SNAKE_CASE_ : Optional[int] = list(json_save_dir.glob('''rank_*.json''' ) ) if intermediate_files: raise ValueError(f'Found files at {json_save_dir} please move or remove them.' ) # In theory, a node could finish and save before another node hits this. If this happens, we can address later. SCREAMING_SNAKE_CASE_ : Dict = {} if args.src_lang is not None: SCREAMING_SNAKE_CASE_ : int = args.src_lang if args.tgt_lang is not None: SCREAMING_SNAKE_CASE_ : Tuple = args.tgt_lang Path(args.save_dir ).mkdir(exist_ok=__a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = eval_data_dir( args.data_dir , __a , args.model_name , type_path=args.type_path , bs=args.bs , fpaa=args.fpaa , task=args.task , local_rank=args.local_rank , n_obs=args.n_obs , max_source_length=args.max_source_length , num_return_sequences=args.num_return_sequences , prefix=args.prefix , dataset_kwargs=__a , **__a , ) if args.local_rank <= 0: SCREAMING_SNAKE_CASE_ : str = Path(args.save_dir ) save_dir.mkdir(exist_ok=__a ) SCREAMING_SNAKE_CASE_ : Dict = gather_results_from_each_node(__a , __a , args.sync_timeout ) SCREAMING_SNAKE_CASE_ : Dict = combine_partial_results(__a ) if args.num_return_sequences > 1: SCREAMING_SNAKE_CASE_ : Any = save_dir.joinpath('''pseudolabel_results.json''' ) print(f'Saving aggregated results at {save_path}, intermediate in {json_save_dir}/' ) save_json(__a , __a ) return SCREAMING_SNAKE_CASE_ : Optional[int] = Path(args.data_dir ).joinpath(args.type_path + '''.target''' ) with open(__a ) as f: SCREAMING_SNAKE_CASE_ : Any = [x.rstrip() for x in f.readlines()][: len(__a )] # Calculate metrics, save metrics, and save _generations.txt SCREAMING_SNAKE_CASE_ : int = '''translation''' in args.task SCREAMING_SNAKE_CASE_ : str = calculate_bleu if calc_bleu else calculate_rouge SCREAMING_SNAKE_CASE_ : Dict = '''bleu''' if calc_bleu else '''rouge''' SCREAMING_SNAKE_CASE_ : Dict = score_fn(__a , __a ) SCREAMING_SNAKE_CASE_ : int = len(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = time.time() - start_time SCREAMING_SNAKE_CASE_ : int = round(runtime / metrics['''n_obs'''] , 4 ) SCREAMING_SNAKE_CASE_ : Dict = num_replicas # TODO(@stas00): add whatever metadata to metrics SCREAMING_SNAKE_CASE_ : str = save_dir.joinpath(f'{args.type_path}_{metric_name}.json' ) save_json(__a , __a , indent=__a ) print(__a ) write_txt_file(__a , save_dir.joinpath(f'{args.type_path}_generations.txt' ) ) if args.debug: write_txt_file(__a , save_dir.joinpath(f'{args.type_path}.target' ) ) else: shutil.rmtree(__a ) def _A (__a ) -> List: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [] for partial_result in partial_results: records.extend(__a ) SCREAMING_SNAKE_CASE_ : int = sorted(__a , key=lambda __a : x["id"] ) SCREAMING_SNAKE_CASE_ : Dict = [x['''pred'''] for x in records] return preds def _A (__a , __a , __a ) -> List[Dict[str, List]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = time.time() logger.info('''waiting for all nodes to finish''' ) SCREAMING_SNAKE_CASE_ : Any = None while (time.time() - start_wait) < timeout: SCREAMING_SNAKE_CASE_ : Optional[int] = list(save_dir.glob('''rank_*.json''' ) ) if len(__a ) < num_replicas: continue try: # make sure all json files are fully saved SCREAMING_SNAKE_CASE_ : int = lmap(__a , __a ) return json_data except JSONDecodeError: continue else: raise TimeoutError('''Rank 0 gave up on waiting for other processes''' ) # Unreachable if __name__ == "__main__": # Usage for MT: run_generate()
91
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
1
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase__ ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) __UpperCamelCase = Features({"text": Value("string" )} ) __UpperCamelCase = Features({"labels": ClassLabel} ) __UpperCamelCase = "text" __UpperCamelCase = "labels" def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Optional[Any]): '''simple docstring''' if self.label_column not in features: raise ValueError(F'Column {self.label_column} is not present in features.') if not isinstance(features[self.label_column] , lowercase_): raise ValueError(F'Column {self.label_column} is not a ClassLabel.') SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(self) SCREAMING_SNAKE_CASE_ : Tuple = self.label_schema.copy() SCREAMING_SNAKE_CASE_ : Any = features[self.label_column] SCREAMING_SNAKE_CASE_ : Any = label_schema return task_template @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return { self.text_column: "text", self.label_column: "labels", }
91
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "ViTImageProcessor" __UpperCamelCase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : str , lowercase_ : Any=None , lowercase_ : Optional[Any]=None , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''feature_extractor''') SCREAMING_SNAKE_CASE_ : 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`.''') super().__init__(lowercase_ , lowercase_) def __call__( self : Optional[Any] , lowercase_ : str=None , lowercase_ : Optional[int]=None , lowercase_ : Dict=None , lowercase_ : List[Any]=None , **lowercase_ : int): '''simple docstring''' if text is None and visual_prompt is None and images is None: raise ValueError('''You have to specify either text, visual prompt or images.''') if text is not None and visual_prompt is not None: raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''') if text is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(lowercase_ , return_tensors=lowercase_ , **lowercase_) if visual_prompt is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_) if images is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_) if visual_prompt is not None and images is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''pixel_values''': image_features.pixel_values, '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: SCREAMING_SNAKE_CASE_ : int = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: SCREAMING_SNAKE_CASE_ : int = { '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**lowercase_) , tensor_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : str , **lowercase_ : List[Any]): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : Union[str, Any] , **lowercase_ : List[str]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowercase_ , ) return self.image_processor_class @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowercase_ , ) return self.image_processor
91
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
1
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging UpperCAmelCase_ : int = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """spiece.model"""} UpperCAmelCase_ : Tuple = { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 UpperCAmelCase_ : List[str] = { """t5-small""": 512, """t5-base""": 512, """t5-large""": 512, """t5-3b""": 512, """t5-11b""": 512, } UpperCAmelCase_ : Optional[int] = """▁""" class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : List[str] , lowercase_ : int="</s>" , lowercase_ : Optional[Any]="<unk>" , lowercase_ : List[Any]="<pad>" , lowercase_ : Union[str, Any]=100 , lowercase_ : Any=None , lowercase_ : Optional[Dict[str, Any]] = None , lowercase_ : List[str]=True , **lowercase_ : Dict , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: SCREAMING_SNAKE_CASE_ : Dict = [F'<extra_id_{i}>' for i in range(lowercase_)] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens SCREAMING_SNAKE_CASE_ : str = len(set(filter(lambda lowercase_: bool('''extra_id''' in str(lowercase_)) , lowercase_))) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''') if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''') SCREAMING_SNAKE_CASE_ : Optional[Any] = legacy SCREAMING_SNAKE_CASE_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowercase_ , unk_token=lowercase_ , pad_token=lowercase_ , extra_ids=lowercase_ , additional_special_tokens=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , legacy=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file SCREAMING_SNAKE_CASE_ : Optional[int] = extra_ids SCREAMING_SNAKE_CASE_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(lowercase_) @staticmethod def _SCREAMING_SNAKE_CASE ( lowercase_ : List[str] , lowercase_ : Tuple , lowercase_ : List[str]): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: SCREAMING_SNAKE_CASE_ : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , lowercase_ , ) return max_model_length @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return self.sp_model.get_piece_size() + self._extra_ids def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) # normal case: some special tokens if token_ids_a is None: return ([0] * len(lowercase_)) + [1] return ([0] * len(lowercase_)) + [1] + ([0] * len(lowercase_)) + [1] def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return list( set(filter(lambda lowercase_: bool(re.search(r'''<extra_id_\d+>''' , lowercase_)) is not None , self.additional_special_tokens))) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' return [self._convert_token_to_id(lowercase_) for token in self.get_sentinel_tokens()] def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[int]): '''simple docstring''' if len(lowercase_) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' ''' eos tokens being added.''') return token_ids else: return token_ids + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos) * [0] return len(token_ids_a + eos + token_ids_a + eos) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self._add_eos_if_not_present(lowercase_) if token_ids_a is None: return token_ids_a else: SCREAMING_SNAKE_CASE_ : Tuple = self._add_eos_if_not_present(lowercase_) return token_ids_a + token_ids_a def __getstate__( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Optional[Any] = None return state def __setstate__( self : Tuple , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Tuple = {} SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : "TextInput" , **lowercase_ : Optional[Any]): '''simple docstring''' if not self.legacy: SCREAMING_SNAKE_CASE_ : int = SPIECE_UNDERLINE + text.replace(lowercase_ , ''' ''') return super().tokenize(lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Optional[Any] , **lowercase_ : List[Any]): '''simple docstring''' if not self.legacy: SCREAMING_SNAKE_CASE_ : List[Any] = text.startswith(lowercase_) if is_first: SCREAMING_SNAKE_CASE_ : List[str] = text[1:] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase_ , out_type=lowercase_) if not self.legacy and not is_first and not text.startswith(''' ''') and tokens[0].startswith(lowercase_): SCREAMING_SNAKE_CASE_ : Any = ([tokens[0][1:]] if len(tokens[0]) > 1 else []) + tokens[1:] return tokens def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Tuple): '''simple docstring''' if token.startswith('''<extra_id_'''): SCREAMING_SNAKE_CASE_ : int = re.match(r'''<extra_id_(\d+)>''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = int(match.group(1)) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : List[str]): '''simple docstring''' if index < self.sp_model.get_piece_size(): SCREAMING_SNAKE_CASE_ : Any = self.sp_model.IdToPiece(lowercase_) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F'<extra_id_{self.vocab_size - 1 - index}>' return token def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [] SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : Tuple = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase_) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : str = [] else: current_sub_tokens.append(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = False out_string += self.sp_model.decode(lowercase_) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : Tuple = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : Any = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ : Any = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Tuple , *lowercase_ : str , **lowercase_ : List[Any]): '''simple docstring''' super().__init__(*lowercase_ , **lowercase_) requires_backends(self , '''vision''') self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str=None , lowercase_ : Dict=None , lowercase_ : Optional[int]=None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = {} SCREAMING_SNAKE_CASE_ : Tuple = {} if prompt is not None: SCREAMING_SNAKE_CASE_ : Tuple = prompt if generate_kwargs is not None: SCREAMING_SNAKE_CASE_ : int = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,''' ''' please use only one''') SCREAMING_SNAKE_CASE_ : Optional[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self : Any , lowercase_ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **lowercase_ : Any): '''simple docstring''' return super().__call__(lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Optional[int] , lowercase_ : List[str]=None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = load_image(lowercase_) if prompt is not None: if not isinstance(lowercase_ , lowercase_): raise ValueError( F'Received an invalid text input, got - {type(lowercase_)} - but expected a single string. ' '''Note also that one single text can be provided for conditional image to text generation.''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.model.config.model_type if model_type == "git": SCREAMING_SNAKE_CASE_ : Dict = self.image_processor(images=lowercase_ , return_tensors=self.framework) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(text=lowercase_ , add_special_tokens=lowercase_).input_ids SCREAMING_SNAKE_CASE_ : Optional[int] = [self.tokenizer.cls_token_id] + input_ids SCREAMING_SNAKE_CASE_ : Tuple = torch.tensor(lowercase_).unsqueeze(0) model_inputs.update({'''input_ids''': input_ids}) elif model_type == "pix2struct": SCREAMING_SNAKE_CASE_ : str = self.image_processor(images=lowercase_ , header_text=lowercase_ , return_tensors=self.framework) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation SCREAMING_SNAKE_CASE_ : int = self.image_processor(images=lowercase_ , return_tensors=self.framework) SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase_ , return_tensors=self.framework) model_inputs.update(lowercase_) else: raise ValueError(F'Model type {model_type} does not support conditional text generation') else: SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor(images=lowercase_ , return_tensors=self.framework) if self.model.config.model_type == "git" and prompt is None: SCREAMING_SNAKE_CASE_ : List[str] = None return model_inputs def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int]=None): '''simple docstring''' if ( "input_ids" in model_inputs and isinstance(model_inputs['''input_ids'''] , lowercase_) and all(x is None for x in model_inputs['''input_ids''']) ): SCREAMING_SNAKE_CASE_ : List[str] = None if generate_kwargs is None: SCREAMING_SNAKE_CASE_ : Optional[int] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. SCREAMING_SNAKE_CASE_ : int = model_inputs.pop(self.model.main_input_name) SCREAMING_SNAKE_CASE_ : Optional[int] = self.model.generate(lowercase_ , **lowercase_ , **lowercase_) return model_outputs def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for output_ids in model_outputs: SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''generated_text''': self.tokenizer.decode( lowercase_ , skip_special_tokens=lowercase_ , ) } records.append(lowercase_) return records
91
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase_ : Dict = {"""configuration_glpn""": ["""GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GLPNConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = ["""GLPNFeatureExtractor"""] UpperCAmelCase_ : Union[str, Any] = ["""GLPNImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[int] = [ """GLPN_PRETRAINED_MODEL_ARCHIVE_LIST""", """GLPNForDepthEstimation""", """GLPNLayer""", """GLPNModel""", """GLPNPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys UpperCAmelCase_ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
1
"""simple docstring""" import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / """utils""")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = mock.Mock() SCREAMING_SNAKE_CASE_ : Optional[Any] = 500 SCREAMING_SNAKE_CASE_ : Any = {} SCREAMING_SNAKE_CASE_ : str = HTTPError SCREAMING_SNAKE_CASE_ : Optional[int] = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE_ : Optional[int] = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''') # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=lowercase_) as mock_head: SCREAMING_SNAKE_CASE_ : List[Any] = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''') # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = mock.Mock() SCREAMING_SNAKE_CASE_ : int = 500 SCREAMING_SNAKE_CASE_ : Any = {} SCREAMING_SNAKE_CASE_ : List[Any] = HTTPError SCREAMING_SNAKE_CASE_ : List[Any] = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE_ : Any = GPTaTokenizerFast.from_pretrained('''gpt2''') # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=lowercase_) as mock_head: SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaTokenizerFast.from_pretrained('''gpt2''') # This check we did call the fake head request mock_head.assert_called() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' try: SCREAMING_SNAKE_CASE_ : Dict = tempfile.mktemp() with open(lowercase_ , '''wb''') as f: http_get('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' , lowercase_) SCREAMING_SNAKE_CASE_ : str = AlbertTokenizer.from_pretrained(lowercase_) finally: os.remove(lowercase_) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('''tokenizer.json'''): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('''tokenizer.json''' , '''wb''') as f: http_get('''https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json''' , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''') # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('''tokenizer.json''') def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = AlbertTokenizer.from_pretrained('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''') @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-tokenizer''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-tokenizer-org''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-tokenizer''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : int = BertTokenizer(lowercase_) tokenizer.push_to_hub('''test-tokenizer''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = BertTokenizer.from_pretrained(F'{USER}/test-tokenizer') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) # Reset repo delete_repo(token=self._token , repo_id='''test-tokenizer''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowercase_ , repo_id='''test-tokenizer''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Dict = BertTokenizer.from_pretrained(F'{USER}/test-tokenizer') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : List[Any] = BertTokenizer(lowercase_) tokenizer.push_to_hub('''valid_org/test-tokenizer-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Tuple = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-tokenizer-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( lowercase_ , repo_id='''valid_org/test-tokenizer-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) @require_tokenizers def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : str = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : List[Any] = CustomTokenizer(lowercase_) # No fast custom tokenizer tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer' , trust_remote_code=lowercase_) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''') # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : Union[str, Any] = BertTokenizerFast.from_pretrained(lowercase_) bert_tokenizer.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = CustomTokenizerFast.from_pretrained(lowercase_) tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : List[Any] = AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer' , trust_remote_code=lowercase_) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizerFast''') SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoTokenizer.from_pretrained( F'{USER}/test-dynamic-tokenizer' , use_fast=lowercase_ , trust_remote_code=lowercase_) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''') class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = Trie() trie.add('''Hello 友達''') self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}}) trie.add('''Hello''') trie.data self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {'''''': 1, ''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}}) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = Trie() self.assertEqual(trie.split('''[CLS] This is a extra_id_100''') , ['''[CLS] This is a extra_id_100''']) trie.add('''[CLS]''') trie.add('''extra_id_1''') trie.add('''extra_id_100''') self.assertEqual(trie.split('''[CLS] This is a extra_id_100''') , ['''[CLS]''', ''' This is a ''', '''extra_id_100''']) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = Trie() trie.add('''A''') self.assertEqual(trie.split('''ABC''') , ['''A''', '''BC''']) self.assertEqual(trie.split('''BCA''') , ['''BC''', '''A''']) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = Trie() trie.add('''TOKEN]''') trie.add('''[SPECIAL_TOKEN]''') self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''') , ['''This is something ''', '''[SPECIAL_TOKEN]''']) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = Trie() trie.add('''A''') trie.add('''P''') trie.add('''[SPECIAL_TOKEN]''') self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''') , ['''This is something ''', '''[SPECIAL_TOKEN]''']) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = Trie() trie.add('''AB''') trie.add('''B''') trie.add('''C''') self.assertEqual(trie.split('''ABC''') , ['''AB''', '''C''']) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = Trie() trie.add('''ABC''') trie.add('''B''') trie.add('''CD''') self.assertEqual(trie.split('''ABCD''') , ['''ABC''', '''D''']) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = Trie() SCREAMING_SNAKE_CASE_ : Optional[int] = trie.cut_text('''ABC''' , [0, 0, 2, 1, 2, 3]) self.assertEqual(lowercase_ , ['''AB''', '''C'''])
91
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
1
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase_ : Tuple = re.compile("""[^A-Za-z_0-9]""") # parameters used in DuplicationIndex UpperCAmelCase_ : List[Any] = 10 UpperCAmelCase_ : List[str] = 256 def _A (__a ) -> Optional[MinHash]: """simple docstring""" if len(__a ) < MIN_NUM_TOKENS: return None SCREAMING_SNAKE_CASE_ : Union[str, Any] = MinHash(num_perm=__a ) for token in set(__a ): min_hash.update(token.encode() ) return min_hash def _A (__a ) -> Set[str]: """simple docstring""" return {t for t in NON_ALPHA.split(__a ) if len(t.strip() ) > 0} class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict , *, lowercase_ : float = 0.85 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = duplication_jaccard_threshold SCREAMING_SNAKE_CASE_ : Any = NUM_PERM SCREAMING_SNAKE_CASE_ : Union[str, Any] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm) SCREAMING_SNAKE_CASE_ : List[Any] = defaultdict(lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Tuple , lowercase_ : MinHash): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self._index.query(lowercase_) if code_key in self._index.keys: print(F'Duplicate key {code_key}') return self._index.insert(lowercase_ , lowercase_) if len(lowercase_) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(lowercase_) break else: self._duplicate_clusters[close_duplicates[0]].add(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [] for base, duplicates in self._duplicate_clusters.items(): SCREAMING_SNAKE_CASE_ : Tuple = [base] + list(lowercase_) # reformat the cluster to be a list of dict SCREAMING_SNAKE_CASE_ : Optional[int] = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(lowercase_) return duplicate_clusters def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.get_duplicate_clusters() with open(lowercase_ , '''w''') as f: json.dump(lowercase_ , lowercase_) def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = element SCREAMING_SNAKE_CASE_ : Dict = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _A (__a ) -> List[Any]: """simple docstring""" with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(__a , max_queue_size=1_00_00 ) , chunksize=1_00 , ): if data is not None: yield data def _A (__a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = DuplicationIndex(duplication_jaccard_threshold=__a ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(__a ) ) , max_queue_size=1_00 ) ): di.add(__a , __a ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _A (__a , __a ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_tokens(__a ) SCREAMING_SNAKE_CASE_ : Any = get_tokens(__a ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase_ : List[str] = None def _A (__a , __a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] for elementa in cluster: SCREAMING_SNAKE_CASE_ : Any = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: SCREAMING_SNAKE_CASE_ : Union[str, Any] = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(__a , __a ) >= jaccard_threshold: elementa["copies"] += 1 break else: SCREAMING_SNAKE_CASE_ : Optional[int] = 1 extremes.append(__a ) return extremes def _A (__a , __a , __a ) -> List[str]: """simple docstring""" global _shared_dataset SCREAMING_SNAKE_CASE_ : Any = dataset SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : str = partial(_find_cluster_extremes_shared , jaccard_threshold=__a ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( __a , __a , ) , total=len(__a ) , ): extremes_list.append(__a ) return extremes_list def _A (__a , __a = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = make_duplicate_clusters(__a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} SCREAMING_SNAKE_CASE_ : Optional[int] = {} SCREAMING_SNAKE_CASE_ : int = find_extremes(__a , __a , __a ) for extremes in extremes_clusters: for element in extremes: SCREAMING_SNAKE_CASE_ : int = element SCREAMING_SNAKE_CASE_ : Optional[int] = duplicate_indices - set(extreme_dict.keys() ) SCREAMING_SNAKE_CASE_ : Any = dataset.filter(lambda __a , __a : idx not in remove_indices , with_indices=__a ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: SCREAMING_SNAKE_CASE_ : Dict = element['''base_index'''] in extreme_dict if element["is_extreme"]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = extreme_dict[element['''base_index''']]['''copies'''] print(f'Original dataset size: {len(__a )}' ) print(f'Number of duplicate clusters: {len(__a )}' ) print(f'Files in duplicate cluster: {len(__a )}' ) print(f'Unique files in duplicate cluster: {len(__a )}' ) print(f'Filtered dataset size: {len(__a )}' ) return ds_filter, duplicate_clusters
91
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''') if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''') if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
1
"""simple docstring""" from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _A (__a , __a ) -> float: """simple docstring""" return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(__a , __a ) ) ) def _A (__a , __a ) -> list[list[list[float] | float]]: """simple docstring""" if dataset.ndim != value_array.ndim: SCREAMING_SNAKE_CASE_ : Tuple = ( '''Wrong input data\'s dimensions... ''' f'dataset : {dataset.ndim}, value_array : {value_array.ndim}' ) raise ValueError(__a ) try: if dataset.shape[1] != value_array.shape[1]: SCREAMING_SNAKE_CASE_ : Any = ( '''Wrong input data\'s shape... ''' f'dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}' ) raise ValueError(__a ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError('''Wrong shape''' ) if dataset.dtype != value_array.dtype: SCREAMING_SNAKE_CASE_ : List[str] = ( '''Input data have different datatype... ''' f'dataset : {dataset.dtype}, value_array : {value_array.dtype}' ) raise TypeError(__a ) SCREAMING_SNAKE_CASE_ : Any = [] for value in value_array: SCREAMING_SNAKE_CASE_ : int = euclidean(__a , dataset[0] ) SCREAMING_SNAKE_CASE_ : List[str] = dataset[0].tolist() for dataset_value in dataset[1:]: SCREAMING_SNAKE_CASE_ : Optional[int] = euclidean(__a , __a ) if dist > temp_dist: SCREAMING_SNAKE_CASE_ : Optional[int] = temp_dist SCREAMING_SNAKE_CASE_ : int = dataset_value.tolist() answer.append([vector, dist] ) return answer def _A (__a , __a ) -> float: """simple docstring""" return np.dot(__a , __a ) / (norm(__a ) * norm(__a )) if __name__ == "__main__": import doctest doctest.testmod()
91
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
1
"""simple docstring""" import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 UpperCAmelCase_ : List[str] = get_tests_dir("""fixtures/dummy_feature_extractor_config.json""") UpperCAmelCase_ : Optional[Any] = get_tests_dir("""fixtures/vocab.json""") UpperCAmelCase_ : List[Any] = get_tests_dir("""fixtures""") class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = 0 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h''') self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : str = WavaVecaConfig() SCREAMING_SNAKE_CASE_ : List[str] = AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h''') # save in new folder model_config.save_pretrained(lowercase_) processor.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , lowercase_)) copyfile(lowercase_ , os.path.join(lowercase_ , '''vocab.json''')) SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : str = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE_ : List[Any] = AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h''') SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaProcessor(lowercase_ , lowercase_) # save in new folder processor.save_pretrained(lowercase_) # drop `processor_class` in tokenizer with open(os.path.join(lowercase_ , lowercase_) , '''r''') as f: SCREAMING_SNAKE_CASE_ : List[Any] = json.load(lowercase_) config_dict.pop('''processor_class''') with open(os.path.join(lowercase_ , lowercase_) , '''w''') as f: f.write(json.dumps(lowercase_)) SCREAMING_SNAKE_CASE_ : List[Any] = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : str = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE_ : int = AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h''') SCREAMING_SNAKE_CASE_ : str = WavaVecaProcessor(lowercase_ , lowercase_) # save in new folder processor.save_pretrained(lowercase_) # drop `processor_class` in feature extractor with open(os.path.join(lowercase_ , lowercase_) , '''r''') as f: SCREAMING_SNAKE_CASE_ : Dict = json.load(lowercase_) config_dict.pop('''processor_class''') with open(os.path.join(lowercase_ , lowercase_) , '''w''') as f: f.write(json.dumps(lowercase_)) SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaConfig(processor_class='''Wav2Vec2Processor''') model_config.save_pretrained(lowercase_) # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , '''vocab.json''')) # create emtpy sample processor with open(os.path.join(lowercase_ , lowercase_) , '''w''') as f: f.write('''{}''') SCREAMING_SNAKE_CASE_ : int = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : str = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''') # If remote code is disabled, we can't load this config. with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) self.assertTrue(processor.special_attribute_present) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') SCREAMING_SNAKE_CASE_ : Tuple = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present) self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''') # Test we can also load the slow version SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_ , use_fast=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present) self.assertEqual(new_tokenizer.__class__.__name__ , '''NewTokenizer''') else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''') def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' try: AutoConfig.register('''custom''' , lowercase_) AutoFeatureExtractor.register(lowercase_ , lowercase_) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_) AutoProcessor.register(lowercase_ , lowercase_) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowercase_): AutoProcessor.register(lowercase_ , lowercase_) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE_ : Union[str, Any] = CustomFeatureExtractor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : List[str] = CustomTokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = CustomProcessor(lowercase_ , lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : str = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = False class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = False class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "AutoFeatureExtractor" __UpperCamelCase = "AutoTokenizer" __UpperCamelCase = False try: AutoConfig.register('''custom''' , lowercase_) AutoFeatureExtractor.register(lowercase_ , lowercase_) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_) AutoProcessor.register(lowercase_ , lowercase_) # If remote code is not set, the default is to use local classes. SCREAMING_SNAKE_CASE_ : int = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''') self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') self.assertFalse(processor.special_attribute_present) self.assertFalse(processor.feature_extractor.special_attribute_present) self.assertFalse(processor.tokenizer.special_attribute_present) # If remote code is disabled, we load the local ones. SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') self.assertFalse(processor.special_attribute_present) self.assertFalse(processor.feature_extractor.special_attribute_present) self.assertFalse(processor.tokenizer.special_attribute_present) # If remote is enabled, we load from the Hub. SCREAMING_SNAKE_CASE_ : Optional[int] = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') self.assertTrue(processor.special_attribute_present) self.assertTrue(processor.feature_extractor.special_attribute_present) self.assertTrue(processor.tokenizer.special_attribute_present) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert''') self.assertEqual(processor.__class__.__name__ , '''BertTokenizerFast''') def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext''') self.assertEqual(processor.__class__.__name__ , '''ConvNextImageProcessor''') @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-processor''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-processor-org''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-processor''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaProcessor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , '''test-processor''') , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : List[str] = WavaVecaProcessor.from_pretrained(F'{USER}/test-processor') for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_)) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab()) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = WavaVecaProcessor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , '''test-processor-org''') , push_to_hub=lowercase_ , use_auth_token=self._token , organization='''valid_org''' , ) SCREAMING_SNAKE_CASE_ : str = WavaVecaProcessor.from_pretrained('''valid_org/test-processor-org''') for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_)) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab()) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() SCREAMING_SNAKE_CASE_ : Optional[int] = CustomFeatureExtractor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : Any = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : List[str] = CustomTokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = CustomProcessor(lowercase_ , lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(F'{USER}/test-dynamic-processor' , token=self._token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = Repository(lowercase_ , clone_from=F'{USER}/test-dynamic-processor' , token=self._token) processor.save_pretrained(lowercase_) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { '''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor''', '''AutoProcessor''': '''custom_processing.CustomProcessor''', } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(lowercase_ , '''tokenizer_config.json''')) as f: SCREAMING_SNAKE_CASE_ : Dict = json.load(lowercase_) self.assertDictEqual( tokenizer_config['''auto_map'''] , { '''AutoTokenizer''': ['''custom_tokenization.CustomTokenizer''', None], '''AutoProcessor''': '''custom_processing.CustomProcessor''', } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(lowercase_ , '''custom_feature_extraction.py'''))) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , '''custom_tokenization.py'''))) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , '''custom_processing.py'''))) repo.push_to_hub() SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained(F'{USER}/test-dynamic-processor' , trust_remote_code=lowercase_) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , '''CustomProcessor''')
91
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
1
"""simple docstring""" class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[str] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = arr.split(''',''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [int(self.array[0])] * len(self.array) SCREAMING_SNAKE_CASE_ : Optional[int] = [int(self.array[0])] * len(self.array) for i in range(1 , len(self.array)): SCREAMING_SNAKE_CASE_ : Dict = max( int(self.array[i]) + sum_value[i - 1] , int(self.array[i])) SCREAMING_SNAKE_CASE_ : int = max(sum_value[i] , rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": UpperCAmelCase_ : Any = input("""please input some numbers:""") UpperCAmelCase_ : int = SubArray(whole_array) UpperCAmelCase_ : Optional[Any] = array.solve_sub_array() print(("""the results is:""", re))
91
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
1
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def _A (__a , __a , __a , __a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = { '''en''': '''Machine learning is great, isn\'t it?''', '''ru''': '''Машинное обучение - это здорово, не так ли?''', '''de''': '''Maschinelles Lernen ist großartig, nicht wahr?''', } # BLUE scores as follows: # "pair": [fairseq, transformers] SCREAMING_SNAKE_CASE_ : Tuple = { '''wmt16-en-de-dist-12-1''': [28.3, 27.52], '''wmt16-en-de-dist-6-1''': [27.4, 27.11], '''wmt16-en-de-12-1''': [26.9, 25.75], } SCREAMING_SNAKE_CASE_ : List[str] = f'{src_lang}-{tgt_lang}' SCREAMING_SNAKE_CASE_ : List[Any] = f'\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "allenai/{model_name}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n' model_card_dir.mkdir(parents=__a , exist_ok=__a ) SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(__a , '''README.md''' ) print(f'Generating {path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(__a ) # make sure we are under the root of the project UpperCAmelCase_ : Union[str, Any] = Path(__file__).resolve().parent.parent.parent UpperCAmelCase_ : Optional[int] = repo_dir / """model_cards""" for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: UpperCAmelCase_ : int = model_cards_dir / """allenai""" / model_name write_model_card(model_card_dir, src_lang="""en""", tgt_lang="""de""", model_name=model_name)
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = KandinskyInpaintPipeline __UpperCamelCase = ["prompt", "image_embeds", "negative_image_embeds", "image", "mask_image"] __UpperCamelCase = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", "mask_image", ] __UpperCamelCase = [ "generator", "height", "width", "latents", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] __UpperCamelCase = False @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return 32 @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return 32 @property def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' return self.time_input_dim @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return self.time_input_dim * 4 @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return 100 @property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base''') return tokenizer @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : str = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) SCREAMING_SNAKE_CASE_ : Any = MultilingualCLIP(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = text_encoder.eval() return text_encoder @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = { '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE_ : List[Any] = UNetaDConditionModel(**lowercase_) return model @property def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' 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 _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Optional[int] = VQModel(**self.dummy_movq_kwargs) return model def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_tokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_unet SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.dummy_movq SCREAMING_SNAKE_CASE_ : List[Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule='''linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=lowercase_ , set_alpha_to_one=lowercase_ , steps_offset=1 , prediction_type='''epsilon''' , thresholding=lowercase_ , ) SCREAMING_SNAKE_CASE_ : List[Any] = { '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Optional[int] , lowercase_ : int=0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(lowercase_)).to(lowercase_) SCREAMING_SNAKE_CASE_ : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1)).to(lowercase_) # create init_image SCREAMING_SNAKE_CASE_ : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowercase_)).to(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE_ : Optional[int] = Image.fromarray(np.uinta(lowercase_)).convert('''RGB''').resize((256, 256)) # create mask SCREAMING_SNAKE_CASE_ : List[Any] = np.ones((64, 64) , dtype=np.floataa) SCREAMING_SNAKE_CASE_ : Any = 0 if str(lowercase_).startswith('''mps'''): SCREAMING_SNAKE_CASE_ : Optional[int] = torch.manual_seed(lowercase_) else: SCREAMING_SNAKE_CASE_ : int = torch.Generator(device=lowercase_).manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = { '''prompt''': '''horse''', '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = '''cpu''' SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : int = self.pipeline_class(**lowercase_) SCREAMING_SNAKE_CASE_ : str = pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**self.get_dummy_inputs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = output.images SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe( **self.get_dummy_inputs(lowercase_) , return_dict=lowercase_ , )[0] SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE_ : str = image_from_tuple[0, -3:, -3:, -1] print(F'image.shape {image.shape}') assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE_ : str = np.array( [0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86]) 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()}' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy''') SCREAMING_SNAKE_CASE_ : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''') SCREAMING_SNAKE_CASE_ : Tuple = np.ones((768, 768) , dtype=np.floataa) SCREAMING_SNAKE_CASE_ : str = 0 SCREAMING_SNAKE_CASE_ : Tuple = '''a hat''' SCREAMING_SNAKE_CASE_ : List[str] = KandinskyPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-prior''' , torch_dtype=torch.floataa) pipe_prior.to(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-inpaint''' , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE_ : List[str] = pipeline.to(lowercase_) pipeline.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.Generator(device='''cpu''').manual_seed(0) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = pipe_prior( lowercase_ , generator=lowercase_ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE_ : str = pipeline( lowercase_ , image=lowercase_ , mask_image=lowercase_ , image_embeds=lowercase_ , negative_image_embeds=lowercase_ , generator=lowercase_ , num_inference_steps=100 , height=768 , width=768 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Tuple = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase_ , lowercase_)
91
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) 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 PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = StableDiffusionSAGPipeline __UpperCamelCase = TEXT_TO_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[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 , ) SCREAMING_SNAKE_CASE_ : Optional[int] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , clip_sample=lowercase_ , set_alpha_to_one=lowercase_ , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : 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 , ) SCREAMING_SNAKE_CASE_ : List[Any] = CLIPTextModel(lowercase_) SCREAMING_SNAKE_CASE_ : int = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') SCREAMING_SNAKE_CASE_ : str = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Optional[Any] , lowercase_ : Tuple=0): '''simple docstring''' if str(lowercase_).startswith('''mps'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(lowercase_) else: SCREAMING_SNAKE_CASE_ : str = torch.Generator(device=lowercase_).manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : str = { '''prompt''': '''.''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 1.0, '''sag_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''') SCREAMING_SNAKE_CASE_ : List[str] = sag_pipe.to(lowercase_) sag_pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = '''.''' SCREAMING_SNAKE_CASE_ : int = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Union[str, Any] = sag_pipe( [prompt] , generator=lowercase_ , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''') SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Dict = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''') SCREAMING_SNAKE_CASE_ : Dict = sag_pipe.to(lowercase_) sag_pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = '''.''' SCREAMING_SNAKE_CASE_ : str = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Union[str, Any] = sag_pipe( [prompt] , generator=lowercase_ , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''') SCREAMING_SNAKE_CASE_ : List[Any] = output.images SCREAMING_SNAKE_CASE_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''') SCREAMING_SNAKE_CASE_ : List[Any] = sag_pipe.to(lowercase_) sag_pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = '''.''' SCREAMING_SNAKE_CASE_ : Tuple = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : str = sag_pipe( [prompt] , width=768 , height=512 , generator=lowercase_ , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : List[str] = output.images assert image.shape == (1, 512, 768, 3)
91
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ : List[str] = { """configuration_time_series_transformer""": [ """TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimeSeriesTransformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = [ """TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TimeSeriesTransformerForPrediction""", """TimeSeriesTransformerModel""", """TimeSeriesTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
1
"""simple docstring""" UpperCAmelCase_ : str = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def _A () -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = input('''Enter message: ''' ) SCREAMING_SNAKE_CASE_ : str = input('''Enter key [alphanumeric]: ''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = input('''Encrypt/Decrypt [e/d]: ''' ) if mode.lower().startswith('''e''' ): SCREAMING_SNAKE_CASE_ : str = '''encrypt''' SCREAMING_SNAKE_CASE_ : List[Any] = encrypt_message(__a , __a ) elif mode.lower().startswith('''d''' ): SCREAMING_SNAKE_CASE_ : Dict = '''decrypt''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = decrypt_message(__a , __a ) print(f'\n{mode.title()}ed message:' ) print(__a ) def _A (__a , __a ) -> str: """simple docstring""" return translate_message(__a , __a , '''encrypt''' ) def _A (__a , __a ) -> str: """simple docstring""" return translate_message(__a , __a , '''decrypt''' ) def _A (__a , __a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : Tuple = key.upper() for symbol in message: SCREAMING_SNAKE_CASE_ : List[Any] = 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(__a ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__a ): SCREAMING_SNAKE_CASE_ : Dict = 0 else: translated.append(__a ) return "".join(__a ) if __name__ == "__main__": main()
91
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = { """uclanlp/visualbert-vqa""": """https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json""", """uclanlp/visualbert-vqa-pre""": """https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json""", """uclanlp/visualbert-vqa-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json""" ), """uclanlp/visualbert-vcr""": """https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json""", """uclanlp/visualbert-vcr-pre""": """https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json""", """uclanlp/visualbert-vcr-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json""" ), """uclanlp/visualbert-nlvr2""": """https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json""", """uclanlp/visualbert-nlvr2-pre""": """https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json""", """uclanlp/visualbert-nlvr2-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json""" ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "visual_bert" def __init__( self : List[Any] , lowercase_ : str=30522 , lowercase_ : Optional[Any]=768 , lowercase_ : str=512 , lowercase_ : Tuple=12 , lowercase_ : str=12 , lowercase_ : int=3072 , lowercase_ : Dict="gelu" , lowercase_ : int=0.1 , lowercase_ : Any=0.1 , lowercase_ : List[str]=512 , lowercase_ : Any=2 , lowercase_ : Optional[int]=0.02 , lowercase_ : List[str]=1e-12 , lowercase_ : Optional[Any]=False , lowercase_ : str=True , lowercase_ : Dict=1 , lowercase_ : str=0 , lowercase_ : Optional[Any]=2 , **lowercase_ : Union[str, Any] , ): '''simple docstring''' super().__init__(pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Any = vocab_size SCREAMING_SNAKE_CASE_ : str = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = hidden_size SCREAMING_SNAKE_CASE_ : List[str] = visual_embedding_dim SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = initializer_range SCREAMING_SNAKE_CASE_ : Any = type_vocab_size SCREAMING_SNAKE_CASE_ : Any = layer_norm_eps SCREAMING_SNAKE_CASE_ : str = bypass_transformer SCREAMING_SNAKE_CASE_ : Union[str, Any] = special_visual_initialize
91
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
1
"""simple docstring""" import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase_ : str = """▁""" UpperCAmelCase_ : List[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = BigBirdTokenizer __UpperCamelCase = BigBirdTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE_ : Any = self.tokenizer_class(lowercase_ , keep_accents=lowercase_) tokenizer.save_pretrained(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = '''<s>''' SCREAMING_SNAKE_CASE_ : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_) , lowercase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_) , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<unk>''') self.assertEqual(vocab_keys[1] , '''<s>''') self.assertEqual(vocab_keys[-1] , '''[MASK]''') self.assertEqual(len(lowercase_) , 1004) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[Any] = '''I was born in 92000, and this is falsé.''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.tokenize(lowercase_) SCREAMING_SNAKE_CASE_ : str = rust_tokenizer.tokenize(lowercase_) self.assertListEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_) self.assertListEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.encode(lowercase_) SCREAMING_SNAKE_CASE_ : str = rust_tokenizer.encode(lowercase_) self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = BigBirdTokenizer(lowercase_ , keep_accents=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.tokenize('''This is a test''') self.assertListEqual(lowercase_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase_) , [285, 46, 10, 170, 382] , ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.convert_tokens_to_ids(lowercase_) self.assertListEqual( lowercase_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.convert_ids_to_tokens(lowercase_) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') @slow def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = '''Hello World!''' SCREAMING_SNAKE_CASE_ : List[Any] = [65, 18536, 2260, 101, 66] self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_)) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) # fmt: off SCREAMING_SNAKE_CASE_ : List[str] = [65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, 66] # noqa: E231 # fmt: on self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_)) @require_torch @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence SCREAMING_SNAKE_CASE_ : List[Any] = list(self.big_tokenizer.get_vocab().keys())[:10] SCREAMING_SNAKE_CASE_ : str = ''' '''.join(lowercase_) SCREAMING_SNAKE_CASE_ : str = self.big_tokenizer.encode_plus(lowercase_ , return_tensors='''pt''' , return_token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = BigBirdConfig(attention_type='''original_full''') SCREAMING_SNAKE_CASE_ : int = BigBirdModel(lowercase_) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**lowercase_) model(**lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.decode(tokenizer('''Paris is the [MASK].''').input_ids) self.assertTrue(decoded_text == '''[CLS] Paris is the[MASK].[SEP]''') @slow def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {'''input_ids''': [[65, 39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114, 66], [65, 448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='''google/bigbird-roberta-base''' , revision='''215c99f1600e06f83acce68422f2035b2b5c3510''' , )
91
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is None: return [1] + ([0] * len(lowercase_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
1
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": UpperCAmelCase_ : str = 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=512, 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 _A (__a ) -> 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_ : int = parser.parse_args() UpperCAmelCase_ : Union[str, Any] = 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)
91
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : str = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_))
91
1
"""simple docstring""" from math import factorial def _A (__a , __a , __a ) -> float: """simple docstring""" if successes > trials: raise ValueError('''successes must be lower or equal to trials''' ) if trials < 0 or successes < 0: raise ValueError('''the function is defined for non-negative integers''' ) if not isinstance(__a , __a ) or not isinstance(__a , __a ): raise ValueError('''the function is defined for non-negative integers''' ) if not 0 < prob < 1: raise ValueError('''prob has to be in range of 1 - 0''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! SCREAMING_SNAKE_CASE_ : Optional[int] = float(factorial(__a ) ) coefficient /= factorial(__a ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("""Probability of 2 successes out of 4 trails""") print("""with probability of 0.75 is:""", end=""" """) print(binomial_distribution(2, 4, 0.7_5))
91
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
1
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _A (__a , __a , __a , __a , __a , __a ) -> np.ndarray: """simple docstring""" if (ksize % 2) == 0: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ksize + 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(__a ): for x in range(__a ): # distance from center SCREAMING_SNAKE_CASE_ : List[str] = x - ksize // 2 SCREAMING_SNAKE_CASE_ : List[str] = y - ksize // 2 # degree to radiant SCREAMING_SNAKE_CASE_ : int = theta / 1_80 * np.pi SCREAMING_SNAKE_CASE_ : str = np.cos(_theta ) SCREAMING_SNAKE_CASE_ : Dict = np.sin(_theta ) # get kernel x SCREAMING_SNAKE_CASE_ : Any = cos_theta * px + sin_theta * py # get kernel y SCREAMING_SNAKE_CASE_ : Dict = -sin_theta * px + cos_theta * py # fill kernel SCREAMING_SNAKE_CASE_ : Tuple = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image UpperCAmelCase_ : str = imread("""../image_data/lena.jpg""") # turn image in gray scale value UpperCAmelCase_ : Optional[int] = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges UpperCAmelCase_ : Optional[int] = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: UpperCAmelCase_ : List[Any] = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) UpperCAmelCase_ : Dict = out / out.max() * 255 UpperCAmelCase_ : Tuple = out.astype(np.uinta) imshow("""Original""", gray) imshow("""Gabor filter with 20x20 mask and 6 directions""", out) waitKey(0)
91
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
1
"""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_ : Any = logging.get_logger(__name__) def _A (__a , __a=False , __a=False ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = '''backbone.''' if is_semantic else '''''' SCREAMING_SNAKE_CASE_ : List[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'{prefix}blocks.{i}.norm1.weight', f'beit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'{prefix}blocks.{i}.norm1.bias', f'beit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (f'{prefix}blocks.{i}.attn.proj.weight', f'beit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (f'{prefix}blocks.{i}.attn.proj.bias', f'beit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'{prefix}blocks.{i}.norm2.weight', f'beit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'{prefix}blocks.{i}.norm2.bias', f'beit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'{prefix}blocks.{i}.mlp.fc1.weight', f'beit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'{prefix}blocks.{i}.mlp.fc1.bias', f'beit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'{prefix}blocks.{i}.mlp.fc2.weight', f'beit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'{prefix}blocks.{i}.mlp.fc2.bias', f'beit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ (f'{prefix}cls_token', '''beit.embeddings.cls_token'''), (f'{prefix}patch_embed.proj.weight', '''beit.embeddings.patch_embeddings.projection.weight'''), (f'{prefix}patch_embed.proj.bias', '''beit.embeddings.patch_embeddings.projection.bias'''), (f'{prefix}pos_embed', '''beit.embeddings.position_embeddings'''), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ('''mask_token''', '''beit.embeddings.mask_token'''), ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ] ) else: # layernorm + classification head rename_keys.extend( [ ('''fc_norm.weight''', '''beit.pooler.layernorm.weight'''), ('''fc_norm.bias''', '''beit.pooler.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def _A (__a , __a , __a=False , __a=False ) -> Union[str, Any]: """simple docstring""" for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE_ : Dict = '''backbone.''' if is_semantic else '''''' # queries, keys and values SCREAMING_SNAKE_CASE_ : List[str] = state_dict.pop(f'{prefix}blocks.{i}.attn.qkv.weight' ) SCREAMING_SNAKE_CASE_ : Optional[int] = state_dict.pop(f'{prefix}blocks.{i}.attn.q_bias' ) SCREAMING_SNAKE_CASE_ : Any = state_dict.pop(f'{prefix}blocks.{i}.attn.v_bias' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE_ : Dict = q_bias SCREAMING_SNAKE_CASE_ : Optional[int] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE_ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE_ : Tuple = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained SCREAMING_SNAKE_CASE_ : Optional[int] = state_dict.pop(f'{prefix}blocks.{i}.gamma_1' ) SCREAMING_SNAKE_CASE_ : Dict = state_dict.pop(f'{prefix}blocks.{i}.gamma_2' ) SCREAMING_SNAKE_CASE_ : int = gamma_a SCREAMING_SNAKE_CASE_ : Union[str, Any] = gamma_a def _A (__a , __a , __a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = dct.pop(__a ) SCREAMING_SNAKE_CASE_ : int = val def _A () -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ : Any = Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def _A (__a , __a , __a=False ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = False if '''rvlcdip''' in checkpoint_url else True SCREAMING_SNAKE_CASE_ : Union[str, Any] = BeitConfig(use_absolute_position_embeddings=__a , use_mask_token=__a ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: SCREAMING_SNAKE_CASE_ : List[str] = 10_24 SCREAMING_SNAKE_CASE_ : Tuple = 40_96 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 24 SCREAMING_SNAKE_CASE_ : Tuple = 16 # labels if "rvlcdip" in checkpoint_url: SCREAMING_SNAKE_CASE_ : Optional[int] = 16 SCREAMING_SNAKE_CASE_ : Optional[int] = '''huggingface/label-files''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''rvlcdip-id2label.json''' SCREAMING_SNAKE_CASE_ : Optional[int] = json.load(open(hf_hub_download(__a , __a , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE_ : Any = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : str = idalabel SCREAMING_SNAKE_CASE_ : Tuple = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.hub.load_state_dict_from_url(__a , map_location='''cpu''' )['''model'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = create_rename_keys(__a , has_lm_head=__a ) for src, dest in rename_keys: rename_key(__a , __a , __a ) read_in_q_k_v(__a , __a , has_lm_head=__a ) # load HuggingFace model SCREAMING_SNAKE_CASE_ : Dict = BeitForMaskedImageModeling(__a ) if has_lm_head else BeitForImageClassification(__a ) model.eval() model.load_state_dict(__a ) # Check outputs on an image SCREAMING_SNAKE_CASE_ : Dict = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=__a ) SCREAMING_SNAKE_CASE_ : int = prepare_img() SCREAMING_SNAKE_CASE_ : List[str] = image_processor(images=__a , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ : List[Any] = encoding['''pixel_values'''] SCREAMING_SNAKE_CASE_ : Any = model(__a ) SCREAMING_SNAKE_CASE_ : Any = outputs.logits # verify logits SCREAMING_SNAKE_CASE_ : Optional[int] = [1, 16] if '''rvlcdip''' in checkpoint_url else [1, 1_96, 81_92] assert logits.shape == torch.Size(__a ), "Shape of logits not as expected" Path(__a ).mkdir(exist_ok=__a ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__a ) if push_to_hub: if has_lm_head: SCREAMING_SNAKE_CASE_ : Optional[Any] = '''dit-base''' if '''base''' in checkpoint_url else '''dit-large''' else: SCREAMING_SNAKE_CASE_ : Dict = '''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(__a , __a ) , organization='''nielsr''' , commit_message='''Add image processor''' , use_temp_dir=__a , ) model.push_to_hub( repo_path_or_name=Path(__a , __a ) , organization='''nielsr''' , commit_message='''Add model''' , use_temp_dir=__a , ) if __name__ == "__main__": UpperCAmelCase_ : str = 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_ : List[Any] = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
91
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
1
"""simple docstring""" import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = SwinConfig.from_pretrained( '''microsoft/swin-tiny-patch4-window7-224''' , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) SCREAMING_SNAKE_CASE_ : Optional[int] = MaskFormerConfig(backbone_config=__a ) SCREAMING_SNAKE_CASE_ : List[Any] = '''huggingface/label-files''' if "ade20k-full" in model_name: # this should be ok SCREAMING_SNAKE_CASE_ : Optional[Any] = 8_47 SCREAMING_SNAKE_CASE_ : int = '''maskformer-ade20k-full-id2label.json''' elif "ade" in model_name: # this should be ok SCREAMING_SNAKE_CASE_ : Optional[int] = 1_50 SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''ade20k-id2label.json''' elif "coco-stuff" in model_name: # this should be ok SCREAMING_SNAKE_CASE_ : Any = 1_71 SCREAMING_SNAKE_CASE_ : List[str] = '''maskformer-coco-stuff-id2label.json''' elif "coco" in model_name: # TODO SCREAMING_SNAKE_CASE_ : List[Any] = 1_33 SCREAMING_SNAKE_CASE_ : List[Any] = '''coco-panoptic-id2label.json''' elif "cityscapes" in model_name: # this should be ok SCREAMING_SNAKE_CASE_ : Dict = 19 SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''cityscapes-id2label.json''' elif "vistas" in model_name: # this should be ok SCREAMING_SNAKE_CASE_ : int = 65 SCREAMING_SNAKE_CASE_ : List[Any] = '''mapillary-vistas-id2label.json''' SCREAMING_SNAKE_CASE_ : Optional[int] = json.load(open(hf_hub_download(__a , __a , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE_ : Any = {int(__a ): v for k, v in idalabel.items()} return config def _A (__a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] # stem # fmt: off rename_keys.append(('''backbone.patch_embed.proj.weight''', '''model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.patch_embed.proj.bias''', '''model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.patch_embed.norm.weight''', '''model.pixel_level_module.encoder.model.embeddings.norm.weight''') ) rename_keys.append(('''backbone.patch_embed.norm.bias''', '''model.pixel_level_module.encoder.model.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm1.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm1.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.relative_position_index', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.proj.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.proj.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm2.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm2.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc1.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc1.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc2.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc2.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias') ) if i < 3: rename_keys.append((f'backbone.layers.{i}.downsample.reduction.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight') ) rename_keys.append((f'backbone.layers.{i}.downsample.norm.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight') ) rename_keys.append((f'backbone.layers.{i}.downsample.norm.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias') ) rename_keys.append((f'backbone.norm{i}.weight', f'model.pixel_level_module.encoder.hidden_states_norms.{i}.weight') ) rename_keys.append((f'backbone.norm{i}.bias', f'model.pixel_level_module.encoder.hidden_states_norms.{i}.bias') ) # FPN rename_keys.append(('''sem_seg_head.layer_4.weight''', '''model.pixel_level_module.decoder.fpn.stem.0.weight''') ) rename_keys.append(('''sem_seg_head.layer_4.norm.weight''', '''model.pixel_level_module.decoder.fpn.stem.1.weight''') ) rename_keys.append(('''sem_seg_head.layer_4.norm.bias''', '''model.pixel_level_module.decoder.fpn.stem.1.bias''') ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((f'sem_seg_head.adapter_{source_index}.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight') ) rename_keys.append((f'sem_seg_head.adapter_{source_index}.norm.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight') ) rename_keys.append((f'sem_seg_head.adapter_{source_index}.norm.bias', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias') ) rename_keys.append((f'sem_seg_head.layer_{source_index}.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight') ) rename_keys.append((f'sem_seg_head.layer_{source_index}.norm.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight') ) rename_keys.append((f'sem_seg_head.layer_{source_index}.norm.bias', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias') ) rename_keys.append(('''sem_seg_head.mask_features.weight''', '''model.pixel_level_module.decoder.mask_projection.weight''') ) rename_keys.append(('''sem_seg_head.mask_features.bias''', '''model.pixel_level_module.decoder.mask_projection.bias''') ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight', f'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias', f'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias') ) # cross-attention out projection rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight', f'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias', f'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias') ) # MLP 1 rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight', f'model.transformer_module.decoder.layers.{idx}.fc1.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias', f'model.transformer_module.decoder.layers.{idx}.fc1.bias') ) # MLP 2 rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight', f'model.transformer_module.decoder.layers.{idx}.fc2.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias', f'model.transformer_module.decoder.layers.{idx}.fc2.bias') ) # layernorm 1 (self-attention layernorm) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight', f'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias', f'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight', f'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias', f'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias') ) # layernorm 3 (final layernorm) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight', f'model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias', f'model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias') ) rename_keys.append(('''sem_seg_head.predictor.transformer.decoder.norm.weight''', '''model.transformer_module.decoder.layernorm.weight''') ) rename_keys.append(('''sem_seg_head.predictor.transformer.decoder.norm.bias''', '''model.transformer_module.decoder.layernorm.bias''') ) # heads on top rename_keys.append(('''sem_seg_head.predictor.query_embed.weight''', '''model.transformer_module.queries_embedder.weight''') ) rename_keys.append(('''sem_seg_head.predictor.input_proj.weight''', '''model.transformer_module.input_projection.weight''') ) rename_keys.append(('''sem_seg_head.predictor.input_proj.bias''', '''model.transformer_module.input_projection.bias''') ) rename_keys.append(('''sem_seg_head.predictor.class_embed.weight''', '''class_predictor.weight''') ) rename_keys.append(('''sem_seg_head.predictor.class_embed.bias''', '''class_predictor.bias''') ) for i in range(3 ): rename_keys.append((f'sem_seg_head.predictor.mask_embed.layers.{i}.weight', f'mask_embedder.{i}.0.weight') ) rename_keys.append((f'sem_seg_head.predictor.mask_embed.layers.{i}.bias', f'mask_embedder.{i}.0.bias') ) # fmt: on return rename_keys def _A (__a , __a , __a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = dct.pop(__a ) SCREAMING_SNAKE_CASE_ : List[Any] = val def _A (__a , __a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ : Dict = state_dict.pop(f'backbone.layers.{i}.blocks.{j}.attn.qkv.weight' ) SCREAMING_SNAKE_CASE_ : List[Any] = state_dict.pop(f'backbone.layers.{i}.blocks.{j}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : List[str] = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE_ : int = in_proj_bias[: dim] SCREAMING_SNAKE_CASE_ : int = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE_ : Any = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE_ : Optional[int] = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE_ : str = in_proj_bias[-dim :] # fmt: on def _A (__a , __a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ : List[Any] = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight' ) SCREAMING_SNAKE_CASE_ : Dict = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE_ : List[Any] = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE_ : Dict = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE_ : Dict = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ : str = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight' ) SCREAMING_SNAKE_CASE_ : Optional[int] = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : Any = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE_ : List[Any] = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE_ : Any = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE_ : List[Any] = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE_ : Optional[Any] = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE_ : Any = in_proj_bias[-hidden_size :] # fmt: on def _A () -> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ : Optional[Any] = Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def _A (__a , __a , __a , __a = False ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = get_maskformer_config(__a ) # load original state_dict with open(__a , '''rb''' ) as f: SCREAMING_SNAKE_CASE_ : Any = pickle.load(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = data['''model'''] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys SCREAMING_SNAKE_CASE_ : Union[str, Any] = create_rename_keys(__a ) for src, dest in rename_keys: rename_key(__a , __a , __a ) read_in_swin_q_k_v(__a , config.backbone_config ) read_in_decoder_q_k_v(__a , __a ) # update to torch tensors for key, value in state_dict.items(): SCREAMING_SNAKE_CASE_ : Optional[int] = torch.from_numpy(__a ) # load 🤗 model SCREAMING_SNAKE_CASE_ : Dict = MaskFormerForInstanceSegmentation(__a ) model.eval() for name, param in model.named_parameters(): print(__a , param.shape ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = model.load_state_dict(__a , strict=__a ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(__a ) == 0, f'Unexpected keys: {unexpected_keys}' # verify results SCREAMING_SNAKE_CASE_ : List[Any] = prepare_img() if "vistas" in model_name: SCREAMING_SNAKE_CASE_ : Tuple = 65 elif "cityscapes" in model_name: SCREAMING_SNAKE_CASE_ : Optional[int] = 6_55_35 else: SCREAMING_SNAKE_CASE_ : int = 2_55 SCREAMING_SNAKE_CASE_ : Any = True if '''ade''' in model_name else False SCREAMING_SNAKE_CASE_ : Optional[int] = MaskFormerImageProcessor(ignore_index=__a , reduce_labels=__a ) SCREAMING_SNAKE_CASE_ : int = image_processor(__a , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = model(**__a ) print('''Logits:''' , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": SCREAMING_SNAKE_CASE_ : int = torch.tensor( [[3.63_53, -4.47_70, -2.60_65], [0.50_81, -4.23_94, -3.53_43], [2.19_09, -5.03_53, -1.93_23]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f'Saving model and image processor to {pytorch_dump_folder_path}' ) Path(__a ).mkdir(exist_ok=__a ) model.save_pretrained(__a ) image_processor.save_pretrained(__a ) if push_to_hub: print('''Pushing model and image processor to the hub...''' ) model.push_to_hub(f'nielsr/{model_name}' ) image_processor.push_to_hub(f'nielsr/{model_name}' ) if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""maskformer-swin-tiny-ade""", type=str, help=("""Name of the MaskFormer model you'd like to convert""",), ) parser.add_argument( """--checkpoint_path""", default="""/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl""", type=str, help="""Path to the original state dict (.pth file).""", ) 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 or not to push the converted model to the 🤗 hub.""" ) UpperCAmelCase_ : Dict = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
91
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
1
"""simple docstring""" 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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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 # ######################################################################## UpperCAmelCase_ : Tuple = 16 UpperCAmelCase_ : List[str] = 32 def _A (__a , __a = 16 ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) SCREAMING_SNAKE_CASE_ : Dict = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ : Any = 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(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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 SCREAMING_SNAKE_CASE_ : str = 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. SCREAMING_SNAKE_CASE_ : Optional[int] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_ : Any = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_ : int = 8 else: SCREAMING_SNAKE_CASE_ : Optional[int] = None return tokenizer.pad( __a , padding='''longest''' , max_length=__a , pad_to_multiple_of=__a , return_tensors='''pt''' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ : Optional[Any] = DataLoader( tokenized_datasets['''train'''] , shuffle=__a , collate_fn=__a , batch_size=__a ) SCREAMING_SNAKE_CASE_ : int = 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 UpperCAmelCase_ : int = mocked_dataloaders # noqa: F811 def _A (__a , __a ) -> Optional[int]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __a ) == "1": SCREAMING_SNAKE_CASE_ : Union[str, Any] = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir ) else: SCREAMING_SNAKE_CASE_ : Dict = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_ : Any = config['''lr'''] SCREAMING_SNAKE_CASE_ : int = int(config['''num_epochs'''] ) SCREAMING_SNAKE_CASE_ : Optional[int] = int(config['''seed'''] ) SCREAMING_SNAKE_CASE_ : Tuple = int(config['''batch_size'''] ) set_seed(__a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = get_dataloaders(__a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE_ : Optional[Any] = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_ : Optional[Any] = 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). SCREAMING_SNAKE_CASE_ : List[str] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_ : List[Any] = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler SCREAMING_SNAKE_CASE_ : int = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=1_00 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # 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. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.prepare( __a , __a , __a , __a , __a ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.split(__a )[-1].split('''.''' )[0] accelerator.init_trackers(__a , __a ) # Now we train the model for epoch in range(__a ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: SCREAMING_SNAKE_CASE_ : Tuple = 0 for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE_ : List[str] = model(**__a ) SCREAMING_SNAKE_CASE_ : Tuple = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() SCREAMING_SNAKE_CASE_ : List[Any] = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : str = model(**__a ) SCREAMING_SNAKE_CASE_ : str = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__a , references=__a , ) SCREAMING_SNAKE_CASE_ : Any = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' , __a ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { '''accuracy''': eval_metric['''accuracy'''], '''f1''': eval_metric['''f1'''], '''train_loss''': total_loss.item() / len(__a ), '''epoch''': epoch, } , step=__a , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 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.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) parser.add_argument( '''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , ) parser.add_argument( '''--project_dir''' , type=__a , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = parser.parse_args() SCREAMING_SNAKE_CASE_ : Optional[int] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__a , __a ) if __name__ == "__main__": main()
91
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
1
"""simple docstring""" def _A (__a ) -> list: """simple docstring""" if len(__a ) < 2: return collection def circle_sort_util(__a , __a , __a ) -> bool: SCREAMING_SNAKE_CASE_ : Tuple = False if low == high: return swapped SCREAMING_SNAKE_CASE_ : Any = low SCREAMING_SNAKE_CASE_ : List[Any] = high while left < right: if collection[left] > collection[right]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = ( collection[right], collection[left], ) SCREAMING_SNAKE_CASE_ : str = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = ( collection[right + 1], collection[left], ) SCREAMING_SNAKE_CASE_ : List[Any] = True SCREAMING_SNAKE_CASE_ : Optional[Any] = low + int((high - low) / 2 ) SCREAMING_SNAKE_CASE_ : Optional[int] = circle_sort_util(__a , __a , __a ) SCREAMING_SNAKE_CASE_ : Optional[int] = circle_sort_util(__a , mid + 1 , __a ) return swapped or left_swap or right_swap SCREAMING_SNAKE_CASE_ : str = True while is_not_sorted is True: SCREAMING_SNAKE_CASE_ : Union[str, Any] = circle_sort_util(__a , 0 , len(__a ) - 1 ) return collection if __name__ == "__main__": UpperCAmelCase_ : int = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase_ : Tuple = [int(item) for item in user_input.split(""",""")] print(circle_sort(unsorted))
91
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
1
"""simple docstring""" def _A (__a , __a ) -> float: """simple docstring""" def get_matched_characters(__a , __a ) -> str: SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): SCREAMING_SNAKE_CASE_ : List[Any] = int(max(0 , i - limit ) ) SCREAMING_SNAKE_CASE_ : List[Any] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(__a ) SCREAMING_SNAKE_CASE_ : Dict = f'{_stra[0:_stra.index(__a )]} {_stra[_stra.index(__a ) + 1:]}' return "".join(__a ) # matching characters SCREAMING_SNAKE_CASE_ : List[str] = get_matched_characters(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_matched_characters(__a , __a ) SCREAMING_SNAKE_CASE_ : int = len(__a ) # transposition SCREAMING_SNAKE_CASE_ : Tuple = ( len([(ca, ca) for ca, ca in zip(__a , __a ) if ca != ca] ) // 2 ) if not match_count: SCREAMING_SNAKE_CASE_ : List[Any] = 0.0 else: SCREAMING_SNAKE_CASE_ : Optional[Any] = ( 1 / 3 * ( match_count / len(__a ) + match_count / len(__a ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("""hello""", """world"""))
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _A (__a , __a ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def _A (__a , __a , __a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = tmp_path / '''cache''' SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def _A (__a , __a , __a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = tmp_path / '''cache''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} SCREAMING_SNAKE_CASE_ : List[str] = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE_ : int = ( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE_ : Dict = ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def _A (__a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = tmp_path / '''cache''' SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} SCREAMING_SNAKE_CASE_ : Optional[Any] = ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def _A (__a , __a , __a ) -> Dict: """simple docstring""" if issubclass(__a , __a ): SCREAMING_SNAKE_CASE_ : Optional[Any] = parquet_path elif issubclass(__a , __a ): SCREAMING_SNAKE_CASE_ : int = [parquet_path] SCREAMING_SNAKE_CASE_ : Dict = tmp_path / '''cache''' SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} SCREAMING_SNAKE_CASE_ : Optional[Any] = ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def _A (__a , __a , __a=("train",) ) -> Any: """simple docstring""" assert isinstance(__a , __a ) for split in splits: SCREAMING_SNAKE_CASE_ : Any = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def _A (__a , __a , __a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = tmp_path / '''cache''' SCREAMING_SNAKE_CASE_ : List[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE_ : int = ParquetDatasetReader( {'''train''': parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def _A (__a , __a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = tmp_path / '''cache''' SCREAMING_SNAKE_CASE_ : Tuple = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} SCREAMING_SNAKE_CASE_ : List[Any] = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE_ : str = ( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE_ : Dict = ParquetDatasetReader({'''train''': parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def _A (__a , __a , __a ) -> Dict: """simple docstring""" if split: SCREAMING_SNAKE_CASE_ : Any = {split: parquet_path} else: SCREAMING_SNAKE_CASE_ : Dict = '''train''' SCREAMING_SNAKE_CASE_ : List[str] = {'''train''': parquet_path, '''test''': parquet_path} SCREAMING_SNAKE_CASE_ : List[Any] = tmp_path / '''cache''' SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} SCREAMING_SNAKE_CASE_ : Tuple = ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = ParquetDatasetWriter(__a , tmp_path / '''foo.parquet''' ) assert writer.write() > 0 SCREAMING_SNAKE_CASE_ : Any = pq.ParquetFile(tmp_path / '''foo.parquet''' ) SCREAMING_SNAKE_CASE_ : Tuple = pf.read() assert dataset.data.table == output_table def _A (__a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = str(shared_datadir / '''test_image_rgb.jpg''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = {'''image''': [image_path]} SCREAMING_SNAKE_CASE_ : Dict = Features({'''image''': Image()} ) SCREAMING_SNAKE_CASE_ : Optional[int] = Dataset.from_dict(__a , features=__a ) SCREAMING_SNAKE_CASE_ : Any = ParquetDatasetWriter(__a , tmp_path / '''foo.parquet''' ) assert writer.write() > 0 SCREAMING_SNAKE_CASE_ : Any = Dataset.from_parquet(str(tmp_path / '''foo.parquet''' ) ) assert dataset.features == reloaded_dataset.features SCREAMING_SNAKE_CASE_ : str = ParquetDatasetReader(str(tmp_path / '''foo.parquet''' ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( '''feature, expected''' , [ (Features({'''foo''': Value('''int32''' )} ), None), (Features({'''image''': Image(), '''foo''': Value('''int32''' )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({'''nested''': Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def _A (__a , __a ) -> str: """simple docstring""" assert get_writer_batch_size(__a ) == expected
91
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
1
"""simple docstring""" from manim import * class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = Rectangle(height=0.5 , width=0.5) SCREAMING_SNAKE_CASE_ : Dict = Rectangle(height=0.46 , width=0.46).set_stroke(width=0) SCREAMING_SNAKE_CASE_ : Any = [mem.copy() for i in range(6)] SCREAMING_SNAKE_CASE_ : Optional[int] = [mem.copy() for i in range(6)] SCREAMING_SNAKE_CASE_ : Optional[int] = VGroup(*lowercase_).arrange(lowercase_ , buff=0) SCREAMING_SNAKE_CASE_ : Optional[int] = VGroup(*lowercase_).arrange(lowercase_ , buff=0) SCREAMING_SNAKE_CASE_ : List[Any] = VGroup(lowercase_ , lowercase_).arrange(lowercase_ , buff=0) SCREAMING_SNAKE_CASE_ : List[str] = Text('''CPU''' , font_size=24) SCREAMING_SNAKE_CASE_ : Optional[Any] = Group(lowercase_ , lowercase_).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_) cpu.move_to([-2.5, -0.5, 0]) self.add(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = [mem.copy() for i in range(1)] SCREAMING_SNAKE_CASE_ : Union[str, Any] = VGroup(*lowercase_).arrange(lowercase_ , buff=0) SCREAMING_SNAKE_CASE_ : List[str] = Text('''GPU''' , font_size=24) SCREAMING_SNAKE_CASE_ : Optional[int] = Group(lowercase_ , lowercase_).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_) gpu.align_to(lowercase_ , lowercase_) gpu.set_x(gpu.get_x() - 1) self.add(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [mem.copy() for i in range(6)] SCREAMING_SNAKE_CASE_ : Tuple = VGroup(*lowercase_).arrange(lowercase_ , buff=0) SCREAMING_SNAKE_CASE_ : Optional[int] = Text('''Model''' , font_size=24) SCREAMING_SNAKE_CASE_ : Tuple = Group(lowercase_ , lowercase_).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_) model.move_to([3, -1.0, 0]) self.play( Create(lowercase_ , run_time=1) , Create(lowercase_ , run_time=1) , Create(lowercase_ , run_time=1) , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = MarkupText( F'First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.' , font_size=24 , ) SCREAMING_SNAKE_CASE_ : Dict = Square(side_length=2.2) key.move_to([-5, 2, 0]) SCREAMING_SNAKE_CASE_ : Union[str, Any] = MarkupText( F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0]) step_a.move_to([2, 2, 0]) self.play(Write(lowercase_ , run_time=2.5) , Write(lowercase_) , Write(lowercase_)) self.add(lowercase_) SCREAMING_SNAKE_CASE_ : Any = [] SCREAMING_SNAKE_CASE_ : Any = [] SCREAMING_SNAKE_CASE_ : List[str] = [] for i, rect in enumerate(lowercase_): SCREAMING_SNAKE_CASE_ : Any = Rectangle(height=0.46 , width=0.46).set_stroke(width=0.0).set_fill(lowercase_ , opacity=0.7) cpu_target.move_to(lowercase_) cpu_target.generate_target() SCREAMING_SNAKE_CASE_ : Optional[int] = 0.46 / 4 SCREAMING_SNAKE_CASE_ : str = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT) , buff=0.02 , direction=lowercase_) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=lowercase_ , buff=0.0) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=lowercase_ , buff=0.0) cpu_targs.append(lowercase_) first_animations.append(rect.animate(run_time=0.5).set_stroke(lowercase_)) second_animations.append(MoveToTarget(lowercase_ , run_time=1.5)) self.play(*lowercase_) self.play(*lowercase_) self.wait()
91
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
1
"""simple docstring""" import math class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int] , lowercase_ : Dict=0): # a graph with Node 0,1,...,N-1 '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = n SCREAMING_SNAKE_CASE_ : Any = [ [math.inf for j in range(0 , lowercase_)] for i in range(0 , lowercase_) ] # adjacency matrix for weight SCREAMING_SNAKE_CASE_ : str = [ [math.inf for j in range(0 , lowercase_)] for i in range(0 , lowercase_) ] # dp[i][j] stores minimum distance from i to j def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = w def _SCREAMING_SNAKE_CASE ( self : Dict): '''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_ : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j]) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Dict , lowercase_ : Optional[Any]): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": UpperCAmelCase_ : List[str] = 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)
91
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
1
"""simple docstring""" from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase_ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase_ : Optional[Any] = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def _A (__a , __a , __a=8 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE_ : Any = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Optional[int] , lowercase_ : UNetaDConditionModel , lowercase_ : DDPMScheduler , lowercase_ : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=lowercase_ , scheduler=lowercase_ , movq=lowercase_ , ) SCREAMING_SNAKE_CASE_ : Tuple = 2 ** (len(self.movq.config.block_out_channels) - 1) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[str] , lowercase_ : Tuple): '''simple docstring''' if latents is None: SCREAMING_SNAKE_CASE_ : Optional[Any] = randn_tensor(lowercase_ , generator=lowercase_ , device=lowercase_ , dtype=lowercase_) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}') SCREAMING_SNAKE_CASE_ : Optional[int] = latents.to(lowercase_) SCREAMING_SNAKE_CASE_ : Any = latents * scheduler.init_noise_sigma return latents def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : int=0): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''') SCREAMING_SNAKE_CASE_ : Dict = torch.device(F'cuda:{gpu_id}') SCREAMING_SNAKE_CASE_ : Optional[Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Dict=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.''') SCREAMING_SNAKE_CASE_ : Tuple = torch.device(F'cuda:{gpu_id}') if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=lowercase_) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE_ : int = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = cpu_offload_with_hook(lowercase_ , lowercase_ , prev_module_hook=lowercase_) # We'll offload the last model manually. SCREAMING_SNAKE_CASE_ : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' if not hasattr(self.unet , '''_hf_hook'''): return self.device for module in self.unet.modules(): if ( hasattr(lowercase_ , '''_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(lowercase_) def __call__( self : Tuple , lowercase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowercase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowercase_ : int = 512 , lowercase_ : int = 512 , lowercase_ : int = 100 , lowercase_ : float = 4.0 , lowercase_ : int = 1 , lowercase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowercase_ : Optional[torch.FloatTensor] = None , lowercase_ : Optional[str] = "pil" , lowercase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self._execution_device SCREAMING_SNAKE_CASE_ : Optional[int] = guidance_scale > 1.0 if isinstance(lowercase_ , lowercase_): SCREAMING_SNAKE_CASE_ : List[str] = torch.cat(lowercase_ , dim=0) SCREAMING_SNAKE_CASE_ : int = image_embeds.shape[0] * num_images_per_prompt if isinstance(lowercase_ , lowercase_): SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cat(lowercase_ , dim=0) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ : Optional[int] = image_embeds.repeat_interleave(lowercase_ , dim=0) SCREAMING_SNAKE_CASE_ : Optional[Any] = negative_image_embeds.repeat_interleave(lowercase_ , dim=0) SCREAMING_SNAKE_CASE_ : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0).to(dtype=self.unet.dtype , device=lowercase_) self.scheduler.set_timesteps(lowercase_ , device=lowercase_) SCREAMING_SNAKE_CASE_ : str = self.scheduler.timesteps SCREAMING_SNAKE_CASE_ : Any = self.unet.config.in_channels SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = downscale_height_and_width(lowercase_ , lowercase_ , self.movq_scale_factor) # create initial latent SCREAMING_SNAKE_CASE_ : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowercase_ , lowercase_ , lowercase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowercase_)): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE_ : Optional[int] = torch.cat([latents] * 2) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE_ : str = {'''image_embeds''': image_embeds} SCREAMING_SNAKE_CASE_ : Optional[Any] = self.unet( sample=lowercase_ , timestep=lowercase_ , encoder_hidden_states=lowercase_ , added_cond_kwargs=lowercase_ , return_dict=lowercase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = noise_pred.split(latents.shape[1] , dim=1) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = noise_pred.chunk(2) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = variance_pred.chunk(2) SCREAMING_SNAKE_CASE_ : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE_ : Tuple = torch.cat([noise_pred, variance_pred_text] , dim=1) if not ( hasattr(self.scheduler.config , '''variance_type''') and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = noise_pred.split(latents.shape[1] , dim=1) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE_ : List[Any] = self.scheduler.step( lowercase_ , lowercase_ , lowercase_ , generator=lowercase_ , )[0] # post-processing SCREAMING_SNAKE_CASE_ : Any = self.movq.decode(lowercase_ , force_not_quantize=lowercase_)['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}') if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE_ : Any = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE_ : Optional[Any] = image.clamp(0 , 1) SCREAMING_SNAKE_CASE_ : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ : int = self.numpy_to_pil(lowercase_) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase_)
91
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''') if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''') if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
1
"""simple docstring""" def _A (__a ) -> list[list[int]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] if len(__a ) == 1: return [nums.copy()] for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Dict = nums.pop(0 ) SCREAMING_SNAKE_CASE_ : List[Any] = permute(__a ) for perm in permutations: perm.append(__a ) result.extend(__a ) nums.append(__a ) return result def _A (__a ) -> Union[str, Any]: """simple docstring""" def backtrack(__a ): if start == len(__a ) - 1: output.append(nums[:] ) else: for i in range(__a , len(__a ) ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = nums[i], nums[start] backtrack(start + 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = nums[i], nums[start] # backtrack SCREAMING_SNAKE_CASE_ : List[str] = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function UpperCAmelCase_ : Any = permutea([1, 2, 3]) print(res) doctest.testmod()
91
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) 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(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase_ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "maskformer-swin" __UpperCamelCase = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Optional[int] , lowercase_ : str=224 , lowercase_ : List[Any]=4 , lowercase_ : Any=3 , lowercase_ : Dict=96 , lowercase_ : int=[2, 2, 6, 2] , lowercase_ : Optional[Any]=[3, 6, 12, 24] , lowercase_ : Optional[Any]=7 , lowercase_ : List[Any]=4.0 , lowercase_ : Dict=True , lowercase_ : List[Any]=0.0 , lowercase_ : List[Any]=0.0 , lowercase_ : Tuple=0.1 , lowercase_ : Optional[Any]="gelu" , lowercase_ : List[str]=False , lowercase_ : List[Any]=0.02 , lowercase_ : Union[str, Any]=1e-5 , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=None , **lowercase_ : str , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : int = image_size SCREAMING_SNAKE_CASE_ : str = patch_size SCREAMING_SNAKE_CASE_ : Tuple = num_channels SCREAMING_SNAKE_CASE_ : str = embed_dim SCREAMING_SNAKE_CASE_ : Optional[int] = depths SCREAMING_SNAKE_CASE_ : Tuple = len(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = num_heads SCREAMING_SNAKE_CASE_ : Dict = window_size SCREAMING_SNAKE_CASE_ : Any = mlp_ratio SCREAMING_SNAKE_CASE_ : List[str] = qkv_bias SCREAMING_SNAKE_CASE_ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : int = hidden_act SCREAMING_SNAKE_CASE_ : Union[str, Any] = use_absolute_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Optional[Any] = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE_ : List[str] = int(embed_dim * 2 ** (len(lowercase_) - 1)) SCREAMING_SNAKE_CASE_ : Tuple = ['''stem'''] + [F'stage{idx}' for idx in range(1 , len(lowercase_) + 1)] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = get_aligned_output_features_output_indices( out_features=lowercase_ , out_indices=lowercase_ , stage_names=self.stage_names)
91
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[int] = {} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "llama" __UpperCamelCase = ["past_key_values"] def __init__( self : Union[str, Any] , lowercase_ : Union[str, Any]=32000 , lowercase_ : Union[str, Any]=4096 , lowercase_ : Tuple=11008 , lowercase_ : Any=32 , lowercase_ : Dict=32 , lowercase_ : Dict=None , lowercase_ : List[str]="silu" , lowercase_ : Dict=2048 , lowercase_ : str=0.02 , lowercase_ : str=1e-6 , lowercase_ : Optional[int]=True , lowercase_ : Optional[Any]=0 , lowercase_ : Any=1 , lowercase_ : Optional[int]=2 , lowercase_ : Tuple=1 , lowercase_ : Optional[int]=False , lowercase_ : Tuple=None , **lowercase_ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = vocab_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : int = num_attention_heads # for backward compatibility if num_key_value_heads is None: SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = num_key_value_heads SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE_ : int = rms_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = pretraining_tp SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : int = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , tie_word_embeddings=lowercase_ , **lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , lowercase_) 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}') SCREAMING_SNAKE_CASE_ : Any = self.rope_scaling.get('''type''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.rope_scaling.get('''factor''' , lowercase_) 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(lowercase_ , lowercase_) or rope_scaling_factor <= 1.0: raise ValueError(F'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}')
91
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
91
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
1
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Tuple , **lowercase_ : Tuple): '''simple docstring''' warnings.warn( '''The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DonutImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
1
"""simple docstring""" import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse("""0.8.3"""): raise Exception("""requires gluonnlp == 0.8.3""") if version.parse(mx.__version__) != version.parse("""1.5.0"""): raise Exception("""requires mxnet == 1.5.0""") logging.set_verbosity_info() UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[int] = """The Nymphenburg Palace is a beautiful palace in Munich!""" def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = { '''attention_cell''': '''multi_head''', '''num_layers''': 4, '''units''': 10_24, '''hidden_size''': 7_68, '''max_length''': 5_12, '''num_heads''': 8, '''scaled''': True, '''dropout''': 0.1, '''use_residual''': True, '''embed_size''': 10_24, '''embed_dropout''': 0.1, '''word_embed''': None, '''layer_norm_eps''': 1e-5, '''token_type_vocab_size''': 2, } SCREAMING_SNAKE_CASE_ : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py SCREAMING_SNAKE_CASE_ : Dict = BERTEncoder( attention_cell=predefined_args['''attention_cell'''] , num_layers=predefined_args['''num_layers'''] , units=predefined_args['''units'''] , hidden_size=predefined_args['''hidden_size'''] , max_length=predefined_args['''max_length'''] , num_heads=predefined_args['''num_heads'''] , scaled=predefined_args['''scaled'''] , dropout=predefined_args['''dropout'''] , output_attention=__a , output_all_encodings=__a , use_residual=predefined_args['''use_residual'''] , activation=predefined_args.get('''activation''' , '''gelu''' ) , layer_norm_eps=predefined_args.get('''layer_norm_eps''' , __a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later SCREAMING_SNAKE_CASE_ : str = '''openwebtext_ccnews_stories_books_cased''' # Specify download folder to Gluonnlp's vocab SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.join(get_home_dir() , '''models''' ) SCREAMING_SNAKE_CASE_ : List[Any] = _load_vocab(__a , __a , __a , cls=__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = nlp.model.BERTModel( __a , len(__a ) , units=predefined_args['''units'''] , embed_size=predefined_args['''embed_size'''] , embed_dropout=predefined_args['''embed_dropout'''] , word_embed=predefined_args['''word_embed'''] , use_pooler=__a , use_token_type_embed=__a , token_type_vocab_size=predefined_args['''token_type_vocab_size'''] , use_classifier=__a , use_decoder=__a , ) original_bort.load_parameters(__a , cast_dtype=__a , ignore_extra=__a ) SCREAMING_SNAKE_CASE_ : List[str] = original_bort._collect_params_with_prefix() # Build our config 🤗 SCREAMING_SNAKE_CASE_ : List[Any] = { '''architectures''': ['''BertForMaskedLM'''], '''attention_probs_dropout_prob''': predefined_args['''dropout'''], '''hidden_act''': '''gelu''', '''hidden_dropout_prob''': predefined_args['''dropout'''], '''hidden_size''': predefined_args['''embed_size'''], '''initializer_range''': 0.02, '''intermediate_size''': predefined_args['''hidden_size'''], '''layer_norm_eps''': predefined_args['''layer_norm_eps'''], '''max_position_embeddings''': predefined_args['''max_length'''], '''model_type''': '''bort''', '''num_attention_heads''': predefined_args['''num_heads'''], '''num_hidden_layers''': predefined_args['''num_layers'''], '''pad_token_id''': 1, # 2 = BERT, 1 = RoBERTa '''type_vocab_size''': 1, # 2 = BERT, 1 = RoBERTa '''vocab_size''': len(__a ), } SCREAMING_SNAKE_CASE_ : List[str] = BertConfig.from_dict(__a ) SCREAMING_SNAKE_CASE_ : str = BertForMaskedLM(__a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(__a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(__a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = hf_param.shape SCREAMING_SNAKE_CASE_ : Optional[int] = to_torch(params[gluon_param] ) SCREAMING_SNAKE_CASE_ : Tuple = gluon_param.shape assert ( shape_hf == shape_gluon ), f'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param SCREAMING_SNAKE_CASE_ : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , '''word_embed.0.weight''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , '''encoder.position_weight''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , '''encoder.layer_norm.beta''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , '''encoder.layer_norm.gamma''' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) SCREAMING_SNAKE_CASE_ : Dict = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): SCREAMING_SNAKE_CASE_ : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention SCREAMING_SNAKE_CASE_ : BertSelfAttention = layer.attention.self SCREAMING_SNAKE_CASE_ : Dict = check_and_map_params( self_attn.key.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) SCREAMING_SNAKE_CASE_ : str = check_and_map_params( self_attn.key.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) SCREAMING_SNAKE_CASE_ : Any = check_and_map_params( self_attn.query.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) SCREAMING_SNAKE_CASE_ : str = check_and_map_params( self_attn.query.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) SCREAMING_SNAKE_CASE_ : Tuple = check_and_map_params( self_attn.value.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = check_and_map_params( self_attn.value.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output SCREAMING_SNAKE_CASE_ : BertSelfOutput = layer.attention.output SCREAMING_SNAKE_CASE_ : List[str] = check_and_map_params( self_output.dense.bias , f'encoder.transformer_cells.{i}.proj.bias' ) SCREAMING_SNAKE_CASE_ : List[str] = check_and_map_params( self_output.dense.weight , f'encoder.transformer_cells.{i}.proj.weight' ) SCREAMING_SNAKE_CASE_ : Any = check_and_map_params( self_output.LayerNorm.bias , f'encoder.transformer_cells.{i}.layer_norm.beta' ) SCREAMING_SNAKE_CASE_ : Tuple = check_and_map_params( self_output.LayerNorm.weight , f'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate SCREAMING_SNAKE_CASE_ : BertIntermediate = layer.intermediate SCREAMING_SNAKE_CASE_ : List[Any] = check_and_map_params( intermediate.dense.bias , f'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) SCREAMING_SNAKE_CASE_ : Any = check_and_map_params( intermediate.dense.weight , f'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output SCREAMING_SNAKE_CASE_ : BertOutput = layer.output SCREAMING_SNAKE_CASE_ : Dict = check_and_map_params( bert_output.dense.bias , f'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = check_and_map_params( bert_output.dense.weight , f'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) SCREAMING_SNAKE_CASE_ : Dict = check_and_map_params( bert_output.LayerNorm.bias , f'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) SCREAMING_SNAKE_CASE_ : str = check_and_map_params( bert_output.LayerNorm.weight , f'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models SCREAMING_SNAKE_CASE_ : int = RobertaTokenizer.from_pretrained('''roberta-base''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.encode_plus(__a )['''input_ids'''] # Get gluon output SCREAMING_SNAKE_CASE_ : List[str] = mx.nd.array([input_ids] ) SCREAMING_SNAKE_CASE_ : int = original_bort(inputs=__a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(__a ) SCREAMING_SNAKE_CASE_ : List[str] = BertModel.from_pretrained(__a ) hf_bort_model.eval() SCREAMING_SNAKE_CASE_ : Dict = tokenizer.encode_plus(__a , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ : List[Any] = hf_bort_model(**__a )[0] SCREAMING_SNAKE_CASE_ : List[Any] = output_gluon[0].asnumpy() SCREAMING_SNAKE_CASE_ : Union[str, Any] = output_hf[0].detach().numpy() SCREAMING_SNAKE_CASE_ : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() SCREAMING_SNAKE_CASE_ : Tuple = np.allclose(__a , __a , atol=1e-3 ) if success: print('''✔️ Both model do output the same tensors''' ) else: print('''❌ Both model do **NOT** output the same tensors''' ) print('''Absolute difference is:''' , __a ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--bort_checkpoint_path""", default=None, type=str, required=True, help="""Path the official Bort params file.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) UpperCAmelCase_ : Optional[Any] = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
91
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = { """facebook/s2t-small-librispeech-asr""": ( """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "speech_to_text" __UpperCamelCase = ["past_key_values"] __UpperCamelCase = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Any , lowercase_ : Optional[Any]=10000 , lowercase_ : Any=12 , lowercase_ : List[str]=2048 , lowercase_ : str=4 , lowercase_ : List[str]=6 , lowercase_ : Optional[int]=2048 , lowercase_ : Any=4 , lowercase_ : List[str]=0.0 , lowercase_ : Union[str, Any]=0.0 , lowercase_ : Optional[Any]=True , lowercase_ : List[str]=True , lowercase_ : str="relu" , lowercase_ : List[str]=256 , lowercase_ : Any=0.1 , lowercase_ : str=0.0 , lowercase_ : Optional[int]=0.0 , lowercase_ : List[Any]=0.02 , lowercase_ : Tuple=2 , lowercase_ : List[Any]=True , lowercase_ : Dict=1 , lowercase_ : Union[str, Any]=0 , lowercase_ : Union[str, Any]=2 , lowercase_ : List[str]=6000 , lowercase_ : List[Any]=1024 , lowercase_ : Optional[int]=2 , lowercase_ : Union[str, Any]=(5, 5) , lowercase_ : Any=1024 , lowercase_ : int=80 , lowercase_ : str=1 , **lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = d_model SCREAMING_SNAKE_CASE_ : Any = encoder_ffn_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = encoder_layers SCREAMING_SNAKE_CASE_ : Optional[int] = encoder_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = decoder_ffn_dim SCREAMING_SNAKE_CASE_ : List[Any] = decoder_layers SCREAMING_SNAKE_CASE_ : str = decoder_attention_heads SCREAMING_SNAKE_CASE_ : Any = dropout SCREAMING_SNAKE_CASE_ : List[str] = attention_dropout SCREAMING_SNAKE_CASE_ : Dict = activation_dropout SCREAMING_SNAKE_CASE_ : Tuple = activation_function SCREAMING_SNAKE_CASE_ : Optional[Any] = init_std SCREAMING_SNAKE_CASE_ : Any = encoder_layerdrop SCREAMING_SNAKE_CASE_ : List[Any] = decoder_layerdrop SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Tuple = encoder_layers SCREAMING_SNAKE_CASE_ : Any = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE_ : Any = max_source_positions SCREAMING_SNAKE_CASE_ : Optional[Any] = max_target_positions SCREAMING_SNAKE_CASE_ : Tuple = num_conv_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(lowercase_) SCREAMING_SNAKE_CASE_ : str = conv_channels SCREAMING_SNAKE_CASE_ : Optional[int] = input_feat_per_channel SCREAMING_SNAKE_CASE_ : List[str] = input_channels if len(self.conv_kernel_sizes) != self.num_conv_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` ''' F'but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes)}`, ' F'`config.num_conv_layers = {self.num_conv_layers}`.') super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , is_encoder_decoder=lowercase_ , decoder_start_token_id=lowercase_ , **lowercase_ , )
91
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
1
"""simple docstring""" from math import isqrt, loga def _A (__a ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __a , __a ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = False return [i for i in range(2 , __a ) if is_prime[i]] def _A (__a = 80_08_00 , __a = 80_08_00 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = degree * loga(__a ) SCREAMING_SNAKE_CASE_ : str = int(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = calculate_prime_numbers(__a ) SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[Any] = 0 SCREAMING_SNAKE_CASE_ : List[Any] = len(__a ) - 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() = }''')
91
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai/whisper-base" __UpperCamelCase = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) __UpperCamelCase = "transcriber" __UpperCamelCase = WhisperProcessor __UpperCamelCase = WhisperForConditionalGeneration __UpperCamelCase = ["audio"] __UpperCamelCase = ["text"] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Union[str, Any]): '''simple docstring''' return self.pre_processor(lowercase_ , return_tensors='''pt''').input_features def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : List[Any]): '''simple docstring''' return self.model.generate(inputs=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : List[str]): '''simple docstring''' return self.pre_processor.batch_decode(lowercase_ , skip_special_tokens=lowercase_)[0]
91
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is None: return [1] + ([0] * len(lowercase_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
1